Python中字符串的格式化方法小结
老办法
Python2.6之前,格式字符串的使用方法相对更简单些,虽然其能够接收的参数数量有限制。这些方法在Python3.3中仍然有效,但已有含蓄的警告称将完全淘汰这些方法,目前还没有明确的时间进度表。
格式化浮点数:
pi=3.14159
print("pi=%1.2f",%pi)
多个替换值:
s1="cats" s2="dogs" s3="%sand%slivingtogether"%(s1,s2)
没有足够的参数:
使用老的格式化方法,我经常犯错"TypeError:notenoughargumentsforformatingstring",因为我数错了替换变量的数量,编写如下这样的代码很容易漏掉变量。
set=(%s,%s,%s,%s,%s,%s,%s,%s)"%(a,b,c,d,e,f,g,h,i)
对于新的Python格式字符串,可以使用编号的参数,这样你就不需要统计有多少个参数。
set=set="({0},{1},{2},{3},{4},{5},{6},{7})".format(a,b,c,d,e,f,g)
Python2.x基于字典字符串格式化
"%(n)d%(x)s"%{"n":1,"x":"spam"}
reply="""
Greetings...
Hello%(name)s!
Youragesquaredis%(age)s
"""
values={'name':'Bob','age':40}
printrely%values
Python3.xformat方法格式化
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])
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下