首頁 > 後端開發 > Python教學 > Python中字符串的格式化方法小结

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
發布: 2016-06-10 15:05:06
原創
1161 人瀏覽過

老办法

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

格式化浮点数:

pi = 3.14159
print(" pi = %1.2f ", % pi)
登入後複製


多个替换值:

s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)
登入後複製

没有足够的参数:

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

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)

登入後複製

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

"%(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方法格式化

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])
登入後複製

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
python - ubuntu16.04 lxml的報錯
來自於 1970-01-01 08:00:00
0
0
0
有辦法在PHP裡寫Python嗎?
來自於 1970-01-01 08:00:00
0
0
0
python scrapy爬蟲錯誤
來自於 1970-01-01 08:00:00
0
0
0
python相關問題求解決,有償
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板