骏马金龙 (新博客:www.junmajinlong.com)

网名骏马金龙,钟情于IT世界里的各种原理和实现机制,强迫症重症患者。爱研究、爱翻译、爱分享。特借此一亩三分田记录自己成长点滴!!!

python字符串格式化输出

分类: python

python中有两种格式化输出字符串的方式:格式化表达式、format()方法。当然,还有一个简化操作的内置format()函数。

它们绝大部分功能都是重复的,熟悉printf的可以考虑使用格式化表达式,否则使用format()更友好些,因为它像处理函数参数一样,但format()有时候可能写的要更复杂。

格式化表达式

格式化表达式类似于printf的风格,在字符串中使用%作为占位符。本文只是介绍python中的一些特性,如有需要请自行搜索printf用法。

>>> who1 = "long"
>>> who2 = "shuai"

>>> "hello %s world" % "your"
'hello your world'

>>> "hello %s world" % who1
'hello long world'

>>> "hello %s world" % (who1)
'hello long world'

>>> "hello %s %s world" % (who1, who2)
'hello long shuai world'

字符串和替换目标之间也使用%分隔,且替换部分可以有多个(使用括号包围),可以使用变量。

替换目标还可以使用字典,这时在字符串中的%占位符可以以key的方式来引用:

>>> "%(name1)s with %(name2)s" % {"name1":"longshuai", "name2":"xiaofang"}
'longshuai with xiaofang'

用字典的形式,可以让表达式格式化更模板化。例如:

>>> reply = """
... hello %(name)s!
... Your age is %(age)d"""
>>>
>>> values = {'name':"longshuai",'age':23}
>>> print(reply % values)

hello longshuai!
Your age is 23

字符串格式化方法:format()

使用format()来格式化字符串时,使用在字符串中使用{}作为占位符,占位符的内容将引用format()中的参数进行替换。可以是位置参数、命名参数或者兼而有之。

看示例就明白了。

# 位置参数
>>> template = '{0}, {1} and {2}'
>>> template.format('long','shuai','gao')
'long, shuai and gao'

# 命名参数
>>> template = '{name1}, {name2} and {name3}'
>>> template.format(name1='long', name2='shuai', name3='gao')
'long, shuai and gao'

# 混合位置参数、命名参数
>>> template = '{name1}, {0} and {name3}'
>>> template.format("shuai", name1='long', name3='gao')
'long, shuai and gao'

需要注意,format()函数中,位置参数必须放在所有的命名参数之前。例如,下面的会报错:

template.format(name1='long', "shuai", name3='gao')

因为字符串中的占位符是直接引用format中的参数属性的,在占位符处可以进行索引取值、方法调用等操作。例如:

>>> import sys
>>> 'My {1[name]} OS is {0.platform}'.format(sys,{"name":"laptop"})
'My laptop OS is win32'

>>> 'My {config[name]} OS is {sys.platform}'.format(sys=sys,config={'name':'loptop'})
'My loptop OS is win32'

但是,在占位符使用索引或切片时,不能使用负数,但可以将负数索引或负数切片放在format的参数中。

>>> s = "hello"
>>> 'first={0[0]}, last={0[4]}'.format(s)
'first=h, last=o'

# 下面是错的
>>> 'first={0[0]}, last={0[-1]}'.format(s)

# 下面是正确的
>>> 'first={0[0]}, last={1}'.format(s, s[-1])
'first=h, last=o'

format()作为函数,它也能进行参数解包,然后提供给占位符。

>>> s=['a','b','c']
>>> '{0}, {1} and {2}'.format(*s)
'a, b and c'

在占位符后面加上数值可以表示占用字符宽度。

>>> '{0:10} = {1:10}'.format('abc','def')
'abc        = def       '

>>> '{0:10} = {1:10}'.format('abc',123)
'abc        =        123'
>>> '{0:10} = {1:10}'.format('abc',123.456)
'abc        =    123.456'

使用>表示右对齐,<表示左对齐,^表示居中对齐,并且可以使用0来填充空格。

>>> '{0:>10} = {1:>10}'.format('abc','def')
'       abc =        def'
>>> '{0:>10} = {1:<10}'.format('abc','def')
'       abc = def       '
>>> '{0:^10} = {1:^10}'.format('abc','def')
'   abc     =    def    '

>>> '{0:10} , {1:<06}'.format('abc','def')
'abc        , def000'
>>> '{0:10} , {1:>06}'.format('abc','def')
'abc        , 000def'
>>> '{0:10} , {1:^06}'.format('abc','def')
'abc        , 0def00'

可以指定e、f、g类型的浮点数,默认采用g浮点数格式化。例如:

>>> '{0:f}, {1:.2f}, {2:06.2f}'.format(3.14159, 3.14159, 3.14159)
'3.141590, 3.14, 003.14'

:.2f表示保留两位小数,:06.2f表示最大长度位6字符,左边使用0填充而不是字符串,保留2位小数。

甚至,可以从format()中指定小数位数。

>>> '{0:.{1}f}'.format(1/3, 4)
'0.3333'

内置函数format()

除了字符串方法format(),还提供了一个快速格式化单个字符串目标的内置函数format()。

用法示例:

>>> '{0:.2f}'.format(1.2345)
'1.23'

>>> format(1.2345, '.2f')
'1.23'

>>> '%.2f' % 1.2345
'1.23'

 

转载请注明出处:https://www.cnblogs.com/f-ck-need-u/p/10139325.html

如果觉得文章不错,不妨给个打赏,写作不易,各位的支持,能激发和鼓励我更大的写作热情。谢谢!

posted @   骏马金龙  阅读(2125)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
# 本文目录:
(右下角 # 关闭目录)
格式化表达式字符串格式化方法:format()内置函数format()
点击右上角即可分享
微信分享提示

感谢您的支持

扫描二维码打赏

支付宝打赏