输出格式化:str.format() 的基本使用

str.format() 的基本使用如下:

>>> print('{}网址: "{}!"'.format('菜鸟教程', 'www.runoob.com')) 菜鸟教程网址: "www.runoob.com!"

括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。

在括号中的数字用于指向传入对象在 format() 中的位置,如下所示:

>>> print('{0} 和 {1}'.format('Google', 'Runoob')) Google  Runoob >>> print('{1} 和 {0}'.format('Google', 'Runoob')) Runoob  Google

如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数。

>>> print('{name}网址: {site}'.format(name='菜鸟教程', site='www.runoob.com')) 菜鸟教程网址: www.runoob.com

位置及关键字参数可以任意的结合:

>>> print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'Runoob', other='Taobao')) 站点列表 Google, Runoob,  Taobao

'!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr()) 可以用于在格式化某个值之前对其进行转化:

>>> import math
>>> print('常量 PI 的值近似为: {}。'.format(math.pi)) 常量 PI 的值近似为: 3.141592653589793 >>> print('常量 PI 的值近似为: {!r}。'.format(math.pi)) 常量 PI 的值近似为: 3.141592653589793

可选项 ':' 和格式标识符可以跟着字段名。 这就允许对值进行更好的格式化。 下面的例子将 Pi 保留到小数点后三位:

>>> import math
>>> print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi)) 常量 PI 的值近似为 3.142

在 ':' 后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用。

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} >>> for name, number in table.items(): ... print('{0:10} ==> {1:10d}'.format(name, number)) ... Runoob ==> 2 Taobao ==> 3 Google ==> 1

如果你有一个很长的格式化字符串, 而你不想将它们分开, 那么在格式化时通过变量名而非位置会是很好的事情。

最简单的就是传入一个字典, 然后使用方括号 '[]' 来访问键值 :

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} >>> print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table)) Runoob: 2; Google: 1; Taobao: 3

也可以通过在 table 变量前使用 '**' 来实现相同的功能:

>>> table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} >>> print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table)) Runoob: 2; Google: 1; Taobao: 3

转载于:https://www.cnblogs.com/zf612326/p/9391645.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值