python格式化输出的几种方式
方法一:format
name = 'Harry'
age = 13.52
'{} is {:.0f}'.format(name, age)
>>>'Harry is 14'
方法二:f
这个是format
形式的方便版
name = 'Harry'
age = 13.52
f'{name} is {age:.0f}'
>>>'Harry is 14'
方法三:%
name = 'Harry'
age = 13.52
'%s is %d' % (name, age)
>>>'Harry is 13'
下面是关于format
的更多细节。
几种映射方式
位置
name = 'Tom'
age = 13
color = 'green'
'{0} is {1}. {0} likes {2} most.'.format(name, age, color)
>>> 'Tom is 13. Tom likes green most.'
关键字参数
name = 'Tom'
age = 13
color = 'green'
'{name} is {age}. {name} likes {color} most.'.format(name=name, age=age, color=color)
>>> 'Tom is 13. Tom likes green most.'
'{name} is {age}. {name} likes {color} most.'.format(name='Harry', age=20, color='blue')
>>> 'Harry is 20. Harry likes blue most.'
关键字参数和对象属性
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
pp = Person('Tome', 13)
'{person.name} is {person.age}'.format(person = pp)
>>> 'Tome is 13'
关键字参数和下标
pp = ['Tome', 13]
'{person[0]} is {person[1]}'.format(person = pp)
>>> 'Tome is 13'
格式
对齐和填充
^、<、>
分别是居中、左对齐、右对齐,后面带宽度
:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
a = 'a'
'{:>8}'.format(a)
>>> ' a'
a = 'a'
'{:0>8}'.format(a)
>>> '0000000a'
精度和类型
这个是大家最常用的,就不再赘述。
'{:.2f}'.format(100.555)
>>> '100.56'
这里可以对比一下字符串和数字在填充和精度上的区别:
'{0:4}'.format(str(5))
>>> '5 '
'{0:4}'.format(5)
>>> ' 5'
参考博文
https://blog.csdn.net/fengzhizi76506/article/details/57492295