字符串的格式化输出可以让我们的工作变得规范化,这是一种十分有效操作,相信在不断的学习中会领悟到它强大的作用。
%
下表展示了一些常用的字符串格式化代码。
代码 | 意义 |
s | 字符串 |
r | 原始形象输出 |
c | 字符,转为ASCII码值 |
d | 十进制(整数) |
i | 整数 |
u | 无号(整数) |
o | 八进制数 |
x | 十六进制数 |
f | 浮点数十进制 |
e | 浮点指数 |
- | 左对齐 |
+ | 正数显示‘+’,负数显示‘-’ |
以上一些是比较常用到的一些字符。字符上还可以对宽度和精度进行设定,如下表所示。
占位符 | 作用 |
%.xf | 表示占位的是一个float,保留x位小数,不足用零补充 |
%Mf | 表示占位的是一个float,如果总长度不足M位,在左边用空格补全,多了不管 |
%Md | 表示占位的是一个int,如果总长度不足M位,在左边用空格补全,多了不管 |
%Ms | 表示占位的是一个str,如果总长度不足M位,在左边用空格补全,多了不管 |
举例:
In [4]: x=123456789
In [5]: '%i**%d**%o**%x**%e**%f' % (x,x,x,x,x,x)
Out[5]: '123456789**123456789**726746425**75bcd15**1.234568e+08**123456789.000000'
In [8]: x=1234 In [9]: '%8d' % x Out[9]: ' 1234' In [10]: '%-8d' % x Out[10]: '1234 ' In [11]: '%2d' % x Out[11]: '1234' In [12]: f=12.456 In [13]: '%f' % f Out[13]: '12.456000' In [14]: '%.4f' % f Out[14]: '12.4560' In [15]: '%8.4f' % f Out[15]: ' 12.4560' In [16]: i=-123 In [17]: '%+d' % i Out[17]: '-123' In [18]: str1='hello' In [20]: '%9s' % str1 Out[20]: ' hello'
format
format用法非常简单,看几个例子。
1 str1="现在是{0}年{1}月{2}日:我是{3}".format(2018,7,27,'AustinJoe--1') 2 print(str1) 3 str2="现在是{y}年{m}月{d}日:我是{name}".format(y=1018,m=7,d=27,name='AustinJoe--2') 4 print(str2) 5 str3="现在是%d年%d月%d日:我是%s" % (2018,7,27,'AustinJoe--3') 6 print(str3) 7 str4="现在是{0}年{1}月{2}日:我是{name}".format(2018,7,27,name='AustinJoe--4') 8 print(str4)
结果
1 现在是2018年7月27日:我是AustinJoe--1 2 现在是1018年7月27日:我是AustinJoe--2 3 现在是2018年7月27日:我是AustinJoe--3 4 现在是2018年7月27日:我是AustinJoe--4
format的用法非常灵活。
添加键、属性和偏移量
1 import sys 2 s='my {1[spam]} runs {0.platform}'.format(sys,{'spam':'laptop'}) 3 print(s)
结果
1 my laptop runs linux
*********************************************************************************************************************************************************************************************************
1 somelist=list('python') 2 s="first ={0[0]},second={0[1]}".format(somelist) 3 print(s)
结果
1 first =p,second=y
添加具体格式化内容
占位符 | 作用 |
{:0} | 十进制转八进制 |
{:x} | 十进制转十六进制 |
{:*>M} | 不足M位在左边用*好这个位的字符补全 |
{:*<M} | 不足M位在右边用*好这个位的字符补全 |
{:*^M} | 不足M位在两边用*好这个位的字符补全 |
In [21]: '{0:*>8}' .format(456) Out[21]: '*****456' In [22]: '{0:*<8}' .format(456) Out[22]: '456*****' In [23]: '{0:*^8}' .format(456) Out[23]: '**456***'
当然位宽度和精度也是可以设置的
In [27]: '{0:.3f}'.format(1.2) Out[27]: '1.200' In [28]: '{0:-8.3f}'.format(1.2) Out[28]: ' 1.200'
除此之外python中还提供format() 这一内置函数。
In [29]: format(1.23,'-8.3f') Out[29]: ' 1.230'