首页 > 编程语言 > 详细

python格式化字符串

时间:2018-10-23 17:06:07      阅读:128      评论:0      收藏:0      [点我收藏+]

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格式化字符串

原文:https://www.cnblogs.com/zhangyafei/p/9837602.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!