源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

python中的格式化输出用法总结

  • 时间:2022-03-17 19:00 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:python中的格式化输出用法总结
本文实例总结了python中的格式化输出用法。分享给大家供大家参考,具体如下: Python一共有两种格式化输出语法。 一种是类似于C语言printf的方式,称为 Formatting Expression
>>> '%s %d-%d' % ('hello', 7, 1)
'hello 7-1'

另一种是类似于C#的方式,称为String Formatting Method Calls
>>> '{0} {1}:{2}'.format('hello', '1', '7')
'hello 1:7'

第一种方式可以指定浮点数的精度,例如
>>> '%.3f' % 1.234567869
'1.235'

[b]运行时动态指定浮点数的精度[/b] 但是当代码在运行中如何动态地通过参数来指定浮点数的精度呢? python的神奇之处在于它又提供了一种非常方便的语法。只需要在 typecode(这里是f)之前加一个 *,浮点数的精度就用它前面的数字来指定。
>>> for i in range(5):
... '%.*f' % (i, 1.234234234234234)
...
'1'
'1.2'
'1.23'
'1.234'
'1.2342'

通过输出结果可以看出,精度都是在运行时动态指定,这样就省去了格式化字符串的拼凑。 使用 String Formatting Method Calls 可以更简洁地完成功能。
>>> for i in range(5):
...  '{0:.{1}f}'.format(1 / 3.0, i)
...
'0'
'0.3'
'0.33'
'0.333'
'0.3333'

[b]实现一个简单的模板工具[/b] Django提供的模板语言,可以让我们通过一个dict(字典)把python变量绑定的html文件中,其实利用python的格式化输出我们也可以仅仅做一个文本替换功能。
>>> replay = """
... Hello World Cup...
... Germany vs Brazil
... %(germany)d : %(brazil)d"""
>>> print(replay % {'germany': 7, 'brazil': 1})
Hello World Cup...
Germany vs Brazil
7 : 1

还可以这样玩
>>> germany = 7
>>> brazil = 1
>>> '%(germany)d : %(brazil)d' % vars()
'7 : 1'

[b]在格式化字符串中访问对象属性和字典键值[/b]
>>> 'My {1[kind]} runs {0.platform}'.format(sys, {'kind': 'pc'})
'My pc runs linux'
>>> 'My {map[kind]} runs {sys.platform}'.format(sys=sys, map={'kind': 'pc'})
'My pc runs linux'

[b]在格式化字符串中通过下标(正整数)访问list元素[/b]
>>> somelist = list('SPAM')
>>> 'first={0[0]}, third={0[2]}'.format(somelist)
'first=S, third=A'
>>> 'first={0}, last={1}'.format(somelist[1], somelist[-1])
'first=P, last=M'
>>> parts = somelist[0], somelist[-1], somelist[1:-1]
>>> 'first={0}, last={1}, middle={2}'.format(*parts)
"first=S, last=M, middle=['P', 'A']"
>>>

更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/645.htm]Python图片操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部