栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 格式化输出format, f,%

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675196.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号