python特有的输出格式

来源:互联网 发布:淘宝上哪家紫砂壶好 编辑:程序博客网 时间:2024/05/16 00:43

Python一共有两种格式化输出语法,
一种是类似于C语言printf的方式,称为 Formatting Expression

print '%s %d-%d' % ('hello', 7, 1)结果:'hello 7-1'

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

print '{0} {1}:{2}'.format('2', '1', '7')结果:print '{0} {1:.1f}:{2}'.format('2', 1, '7')结果:2 1.0:7

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

print '%.3f' % 1.234567869  结果:'1.235'  

运行时动态指定浮点数的精度
但是当代码在运行中如何动态地通过参数来指定浮点数的精度呢?
python的神奇之处在于它又提供了一种非常方便的语法。只需要在 typecode(这里是f)之前加一个 *,浮点数的精度就用它前面的数字来指定。

for i in range(5):    print '%.*f'%(i,1.23456789)结果:11.21.231.2351.2346

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

for i in range(0,5):    print '{0:.{1}f}'.format(1/3.0,i)结果:00.30.330.3330.3333
0 0