這篇文章主要為大家展示了“Python中字符串格式化的方法有哪些”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Python中字符串格式化的方法有哪些”這篇文章吧。

起步
在 Python 中,提供了很多種字符串格式化的方式,分別是 %-formatting、str.format 和 f-string 。
%- 格式化
這種格式化方式來(lái)自于 C 語(yǔ)言風(fēng)格的 sprintf 形式:
name = "weapon" "Hello, %s." % name
C 語(yǔ)言的給實(shí)話風(fēng)格深入人心,通過(guò) % 進(jìn)行占位。
為什么 %-formatting不好
不好的地方在于,如果字符串較長(zhǎng)或較多的參數(shù),那么可讀性就變得很差。
str.format 格式化
PEP-3101 帶來(lái)了 str.format ,它是對(duì) %-formatting 的改進(jìn)。它使用正常的函數(shù)調(diào)用語(yǔ)法,并且可以通過(guò)對(duì)要轉(zhuǎn)換為字符串的對(duì)象的 __format __() 方法進(jìn)行擴(kuò)展。
"Hello, {}. You are {}.".format(name, age)并支持字典形式傳參,免于位置參數(shù)帶來(lái)的麻煩:
"Hello, {name}. You are {age}.".format(name=name, age=age)這兩種方式代碼效果相同,只是第一種方法需要嚴(yán)格控制傳入的參數(shù)位置,而第二種方法沒(méi)有這種限制, 并增加了代碼的可讀性。各種技巧可查看 Format Specification Mini-Language
為什么 str.format() 并不好
雖然它解決了字符串冗長(zhǎng)情況下的可讀性,但需要對(duì)字典傳參基本是要重寫(xiě)一遍變量名,不夠優(yōu)雅。
f-string 格式化
PEP-0498 帶來(lái)了 f-string 方式,它從 Python3.6 開(kāi)始支持。這種方式也是使用 __format__ 協(xié)議進(jìn)行格式化。
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."語(yǔ)法上與 str.format() 類似,但更為簡(jiǎn)潔,當(dāng)字符串較長(zhǎng)時(shí)也不會(huì)繁瑣。更強(qiáng)大的是它支持任意的表達(dá)式。我們可以在花括號(hào)內(nèi)進(jìn)行四則運(yùn)算或函數(shù)調(diào)用等:f"{2 * 6}" 或者 f"{name.lower()} is funny" 。
并且它性能也最好。
幾種格式化方式性能比較
import timeit
def add():
status = 200
body = 'hello world'
return 'Status: ' + str(status) + '\r\n' + body + '\r\n'
def old_style():
status = 200
body = 'hello world'
return 'Status: %s\r\n%s\r\n' % (status, body)
def formatter1():
status = 200
body = 'hello world'
return 'Status: {}\r\n{}\r\n'.format(status, body)
def formatter2():
status = 200
body = 'hello world'
return 'Status: {status}\r\n{body}\r\n'.format(status=status, body=body)
def f_string():
status = 200
body = 'hello world'
return f'Status: {status}\r\n{body}\r\n'
perf_dict = {
'add': min(timeit.repeat(lambda: add())),
'old_style': min(timeit.repeat(lambda: old_style())),
'formatter1': min(timeit.repeat(lambda: formatter1())),
'formatter2': min(timeit.repeat(lambda: formatter2())),
'f_string': min(timeit.repeat(lambda: f_string())),
}
print(perf_dict)結(jié)果:
{
'add': 0.8815229000000002,
'old_style': 0.6351808999999999,
'formatter1': 0.7536176999999995,
'formatter2': 1.2277180999999997,
'f_string': 0.4891379000000011
}f-string 格式化的方式性能最好。
為何 f-string 速度如此快
從指令來(lái)看,f'Status: {status}\r\n{body}\r\n' 翻譯成:
8 LOAD_CONST 3 ('Status: ')
10 LOAD_FAST 0 (status)
12 FORMAT_VALUE 0
14 LOAD_CONST 4 ('\r\n')
16 LOAD_FAST 1 (body)
18 FORMAT_VALUE 0
20 LOAD_CONST 4 ('\r\n')
22 BUILD_STRING 5正如指令中所示的,f-string 是運(yùn)行時(shí)渲染的,底層中轉(zhuǎn)成了類似 "Status: " + status+ "\r\n" + body + "\r\n" 的形式。正如 PEP-0498 中提到的:
F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.
而其他方式則是要先創(chuàng)建字符串常量值,再進(jìn)行替換之類的操作。
以上是“Python中字符串格式化的方法有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
新聞名稱:Python中字符串格式化的方法有哪些-創(chuàng)新互聯(lián)
文章分享:http://chinadenli.net/article22/geocc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、網(wǎng)站制作、營(yíng)銷型網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、ChatGPT、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容