python格式化字符串,,python格式化字


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 张亚飞 ,age23In [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.12In [75]: print(‘{0:b}‘.format(10))  #二进制1010In [76]: print(‘{0:o}‘.format(10))  #十进制12In [77]: print(‘{0:x}‘.format(10))   #十六进制aIn [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格式化字符串

评论关闭