首页 / PYTHON / python格式化字符串
python格式化字符串
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python格式化字符串,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1852字,纯文字阅读大概需要3分钟。
内容图文
![python格式化字符串](/upload/InfoBanner/zyjiaocheng/850/e3b6bd0c04d9440c8559fb831777f24d.jpg)
python格式化字符串的方式
方法一(%)
# 格式的字符串与被格式化的字符串必须一一对应,需格式化的字符串多时,容易搞混
print('hello %s, you sex is %s.' %('tab', 'boy'))
# hello tab, you sex is boy.
print('hello %s, you sex is %s.' %('boy', 'tab'))
# hello boy, you sex is tab.
# 通过字典方式格式化,哪个字符将会格式化到哪里,清晰命了
print('hello %(name)s, you sex is %(sex)s.' %{'name': 'tab', 'sex': 'boy'})
# hello tab, you sex is boy.
args = {'name': 'tab', 'sex': 'boy'}
print('hello %(name)s, you sex is %(sex)s.' %(args))
# hello tab, you sex is boy.
#方法二(.format)
# 方式一:使用位置参数
In [62]: print('My name is {} ,age{}'.format('张亚飞',23)) My name is 张亚飞 ,age23 In [63]: print('My name is {0} ,age{1}'.format('张亚飞',23)) My name is 张亚飞 ,age23
方式二:用字典方式格式化时,指定格式化字符时的位置可以调换
print('hello {name}, you sex is {sex}.'.format(sex='boy', name='tab')) # hello tab, you sex is boy.
# '**'起到解包的作用
args = {'name': 'tab', 'sex': 'boy'}
print('hello {name}, you sex is {sex}.'.format(**args))
方式三:填充与格式化
[填充字符][对齐方式 <^>][宽度]
In [70]: print('{0:*<10}'.format('张亚飞')) 张亚飞******* In [71]: print('{0:*>10}'.format('张亚飞')) *******张亚飞 In [72]: print('{0:*^10}'.format('张亚飞')) ***张亚飞****
方式四:精度与进制
In [74]: print('{0:.2f}'.format(1232132.12321)) #精确到小数点后两位 1232132.12 In [75]: print('{0:b}'.format(10)) #二进制 1010 In [76]: print('{0:o}'.format(10)) #十进制 12 In [77]: print('{0:x}'.format(10)) #十六进制 a In [78]: print('{0:,}'.format(123232244324)) #千分位格式化 123,232,244,324
方式五:使用索引
In [80]: l1 = ['张亚飞',23] In [85]: l2 = ['hobby','打篮球'] In [86]: print('{0[0]}age is {0[1]},{1[0]}is{1[1]}'.format(l1,l2)) 张亚飞age is 23,hobbyis打篮球
推荐使用 .format 方法进行格式化字符串,一来清晰明了,二来效率更高(format 是字符串
str 内置的方法)。更多关于 .format 的用法文档,用户可在交互模式下(终端输入 python
# or ipython or bpython ) 输入 help(str.format) 查看
内容总结
以上是互联网集市为您收集整理的python格式化字符串全部内容,希望文章能够帮你解决python格式化字符串所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。