python的str.format方法

format方法被用于字符串的格式化输出。python

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

可见字符串中大括号内的数字分别对应着format的几个参数。函数

 

若省略数字:spa

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

能够获得一样的输出结果。可是替换顺序默认按照[0],[1],[2]...进行。code

 

若替换{0}和{1}:orm

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

 

输出字符串:blog

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

 

精度控制:it

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

 

宽度控制:form

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

 

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

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              南京航空航天大学
相关文章
相关标签/搜索