python的str.format方法

被用于字符串的格式化输出

1  print('{0}+{1}={2}'.format(1,2,1+2))   #in
2 1+2=3   #out
View Code

大括号里对应参数

若省略数字:

print('{}+{}={}'.format(1,2,1+2))   #in

可以得到同样的输出结果。但是替换顺序默认按照[0],[1],[2]...进行。

若替换{0}和{1}:

print('{1}+{0}={2}'.format(1,2,1+2))   #in
2+1=3   #out

输出字符串:

print('{0} am {1}'.format('i','alex'))  
i am alex   #out

输出参数的值:

1 length = 4
2 name = 'alex'
3 print('the length of {0} is {1}'.format(name,length))
the length of alex is 4

精度控制:

print('{0:.3}'.format(1/3))
0.333

宽度控制:

print('{0:7}{1:7}'.format('use','python'))
use    python 

精宽度控制(宽度内居左):

print('{0:<7.3}..'.format(1/3))   
0.333  ..

其实精宽度控制很类似于C中的printf函数。

同理'>'为居右,'^'为居中。符号很形象。

补全:

复制代码
 1 #!/usr/bin/python
 2 #python3.6
 3 print('{0:0>3}'.format(1)) #居右,左边用0补全
 4 print('{0:{1}>3}'.format(1,0))  #也可以这么写
 5 #当输出中文使用空格补全的时候,系统会自动调用英文空格,这可能会造成不对齐
 6 #for example
 7 blog = {'1':'中国石油大学','2':'浙江大学','3':'南京航空航天大学'}
 8 print('不对齐:')
 9 print('{0:^4}\t\t{1:^8}'.format('序号','名称'))
10 for no,name in blog.items(): #字典的items()方法返回一个键值对,分别赋值给no和name
11     print('{0:^4}\t\t{1:^8}'.format(no,name))
12 print('\n对齐:')
13 print('{0:^4}\t\t{1:{2}^8}'.format('序号','名称',chr(12288))) #chr(12288)为UTF-8中的中文空格
14 for no,name in blog.items():
15     print('{0:^4}\t\t{1:{2}^8}'.format(no,name,chr(12288)))
复制代码
复制代码
#out
001
001
不对齐:
 序号              名称   
 1               中国石油大学 
 2                浙江大学  
 3              南京航空航天大学

对齐:
 序号              名称   
 1               中国石油大学 
 2                浙江大学  
 3              南京航空航天大学

猜你喜欢

转载自www.cnblogs.com/dr228912353/p/9141516.html