python中format格式化字符串比 % 提供更加强大的输出特性
1、位置参数
format的元素输出流位置参数不受顺序约束,元素放置方式为{},只要format里有相对应的参数值即可,参数索引从0开始,传入位置参数列表时可用*进行读取
>>> myinfo = ['oldpan',22]
>>> print('my name is {}, age {}'.format('oldpan', 22))
my name is oldpan, age 22
>>> print('my name is {1}, age {0}'.format(22,'oldpan'))
my name is oldpan, age 22
>>> print('my name is {1}, age {0},and they often call me {1},'.format(22,'oldpan'))
my name is oldpan, age 22,and they often call me oldpan,
>>> print('my name is {}, age {}'.format(*myinfo))
my name is oldpan, age 22
2、使用关键字操作
只要关键字对的上,format也可以像字典一样进行操作
>>> myinfo = {'name':'oldpan','age':22}
>>> print('my name is {name}, age {age}'.format(name='oldpan', age=22))
my name is oldpan, age 22
>>> print('my name is {name}, age {age}'.format(**myinfo))
my name is oldpan, age 22
3、填充与格式化
使用格式为: [填充字符][对齐方式 <^>][宽度]
>>> '{0:*>10}'.format(10) # 右对齐
'********10'
>>> '{0:*<10}'.format(10) # 左对齐
'10********'
>>> '{0:*^10}'.format(10) # 居中对齐
'****10****'
4、精度与进制
>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10) # 二进制
'1010'
>>> '{0:o}'.format(10) # 八进制
'12'
>>> '{0:x}'.format(10) # 16进制
'a'
>>> '{:,}'.format(12369132698) # 千分位格式化
'12,369,132,698'
5、使用索引
>>> li
['hoho', 18]
>>> 'name is {0[0]} age is {0[1]}'.format(li)
'name is hoho age is 18