python 格式化输出format, f,%

python 格式化输出format, f,%,第1张

python 格式化输出format, f,%

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'

参考博文
https://blog.csdn.net/fengzhizi76506/article/details/57492295

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5680401.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存