gpt4 book ai didi

Python中字符串的格式化方法小结

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 24 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Python中字符串的格式化方法小结由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

老办法 。

Python2.6之前,格式字符串的使用方法相对更简单些,虽然其能够接收的参数数量有限制。这些方法在Python3.3中仍然有效,但已有含蓄的警告称将完全淘汰这些方法,目前还没有明确的时间进度表.

格式化浮点数:

?
1
2
pi = 3.14159
print ( " pi = %1.2f " , % pi)

多个替换值:

?
1
2
3
s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)

没有足够的参数:

使用老的格式化方法,我经常犯错"TypeError: not enough arguments for formating string",因为我数错了替换变量的数量,编写如下这样的代码很容易漏掉变量.

?
1
set = ( % s, % s, % s, % s, % s, % s, % s, % s) " % (a,b,c,d,e,f,g,h,i)

对于新的Python格式字符串,可以使用编号的参数,这样你就不需要统计有多少个参数.

?
1
set = set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) " . format (a,b,c,d,e,f,g)

Python 2.x 基于字典字符串格式化 。

?
1
2
3
4
5
6
7
8
"%(n)d %(x)s" % { "n" : 1 , "x" : "spam" }
reply = """
Greetings...
Hello %(name)s!
Your age squared is %(age)s
"""
values = { 'name' : 'Bob' , 'age' : 40 }
print rely % values

Python 3.x format方法格式化 。

?
1
2
3
4
5
6
7
8
9
10
template = '{0},{1} and {2}'
template. format ( 'spam' , 'ham' , 'eggs' )
 
template = '{motto}, {pork} and {food}'
template. format (motto = 'spam' , pork = 'ham' , food = 'eggs' )
 
template = '{motto}, {0} and {food}'
template. format ( 'ham' , motto = 'spam' , food = 'eggs' )
 
'{motto}, {0} and {food}' . format ( 42 , motto = 3.14 , food = [ 1 , 2 , 3 ])

最后此篇关于Python中字符串的格式化方法小结的文章就讲到这里了,如果你想了解更多关于Python中字符串的格式化方法小结的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com