python中str.format方法_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 南京航空航天大学

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值