Python format 格式化输出语法讲解

17 篇文章 2 订阅

Python一共有两种格式化输出语法,

一种是类似于C语言printf的方式,称为 Formatting Expression

[python]  view plain  copy
 print ?
  1. >>> '%s %d-%d' % ('hello'71)  
  2. 'hello 7-1'  


另一种是类似于C#的方式,称为 String Formatting Method Calls

[python]  view plain  copy
 print ?
  1. >>> '{0} {1}:{2}'.format('hello''1''7')  
  2. 'hello 1:7'  

第一种方式可以指定浮点数的精度,例如

[python]  view plain  copy
 print ?
  1. >>> '%.3f' % 1.234567869  
  2. '1.235'  


运行时动态指定浮点数的精度

但是当代码在运行中如何动态地通过参数来指定浮点数的精度呢?

python的神奇之处在于它又提供了一种非常方便的语法。只需要在 typecode(这里是f)之前加一个 *,浮点数的精度就用它前面的数字来指定。

[python]  view plain  copy
 print ?
  1. >>> for i in range(5):  
  2. ...  '%.*f' % (i, 1.234234234234234)  
  3. ...   
  4. '1'  
  5. '1.2'  
  6. '1.23'  
  7. '1.234'  
  8. '1.2342'  

通过输出结果可以看出,精度都是在运行时动态指定,这样就省去了格式化字符串的拼凑。

使用 String Formatting Method Calls 可以更简洁地完成功能。

[python]  view plain  copy
 print ?
  1. >>> for i in range(5):  
  2. ...   '{0:.{1}f}'.format(1 / 3.0, i)  
  3. ...   
  4. '0'  
  5. '0.3'  
  6. '0.33'  
  7. '0.333'  
  8. '0.3333'  


实现一个简单的模板工具

Django提供的模板语言,可以让我们通过一个dict(字典)把python变量绑定的html文件中,其实利用python的格式化输出我们也可以仅仅做一个文本替换功能。

[python]  view plain  copy
 print ?
  1. >>> replay = """ 
  2. ... Hello World Cup... 
  3. ... Germany vs Brazil  
  4. ... %(germany)d : %(brazil)d"""  
  5.   
  6. >>> print(replay % {'germany'7'brazil'1})  
  7.   
  8. Hello World Cup...  
  9. Germany vs Brazil   
  10. 7 : 1  

还可以这样玩

[python]  view plain  copy
 print ?
  1. >>> germany = 7  
  2. >>> brazil = 1  
  3. >>> '%(germany)d : %(brazil)d' % vars()  
  4. '7 : 1'  

在格式化字符串中访问对象属性和字典键值

[python]  view plain  copy
 print ?
  1. >>> 'My {1[kind]} runs {0.platform}'.format(sys, {'kind''pc'})  
  2. 'My pc runs linux'  
  3. >>> 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind''pc'})  
  4. 'My pc runs linux'  

在格式化字符串中通过下标(正整数)访问list元素

[python]  view plain  copy
 print ?
  1. >>> somelist = list('SPAM')  
  2. >>> 'first={0[0]}, third={0[2]}'.format(somelist)  
  3. 'first=S, third=A'  
  4. >>> 'first={0}, last={1}'.format(somelist[1], somelist[-1])  
  5. 'first=P, last=M'  
  6. >>> parts = somelist[0], somelist[-1], somelist[1:-1]  
  7. >>> 'first={0}, last={1}, middle={2}'.format(*parts)  
  8. "first=S, last=M, middle=['P', 'A']"  
  9. >>>   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值