淺析Python 中幾種字符串格式化方法及其比較
起步
在 Python 中,提供了很多種字符串格式化的方式,分別是 %-formatting、str.format 和 f-string 。本文將比較這幾種格式化方法。
%- 格式化
這種格式化方式來自于 C 語言風(fēng)格的 sprintf 形式:
name = "weapon" "Hello, %s." % name
C 語言的給實(shí)話風(fēng)格深入人心,通過 % 進(jìn)行占位。
為什么 %-formatting不好
不好的地方在于,如果字符串較長(zhǎng)或較多的參數(shù),那么可讀性就變得很差。
str.format 格式化
PEP-3101 帶來了 str.format ,它是對(duì) %-formatting 的改進(jìn)。它使用正常的函數(shù)調(diào)用語法,并且可以通過對(duì)要轉(zhuǎn)換為字符串的對(duì)象的 __format __() 方法進(jìn)行擴(kuò)展。
"Hello, {}. You are {}.".format(name, age)
并支持字典形式傳參,免于位置參數(shù)帶來的麻煩:
"Hello, {name}. You are {age}.".format(name=name, age=age)
這兩種方式代碼效果相同,只是第一種方法需要嚴(yán)格控制傳入的參數(shù)位置,而第二種方法沒有這種限制, 并增加了代碼的可讀性。各種技巧可查看 Format Specification Mini-Language
為什么 str.format() 并不好
雖然它解決了字符串冗長(zhǎng)情況下的可讀性,但需要對(duì)字典傳參基本是要重寫一遍變量名,不夠優(yōu)雅。
f-string 格式化
PEP-0498 帶來了 f-string 方式,它從 Python3.6 開始支持。這種方式也是使用 __format__ 協(xié)議進(jìn)行格式化。
name = "Eric" age = 74 f"Hello, {name}. You are {age}."
語法上與 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 速度如此快
從指令來看,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)行替換之類的操作。
總結(jié)
我們?nèi)匀豢梢允褂靡郧暗姆绞竭M(jìn)行格式化,但在此推薦 f-string 方式,因?yàn)樗褂酶?jiǎn)潔,更易讀且更方便,性能又更好,完全沒理由拒絕啊。
從今天開始使用 f-string!
以上所述是小編給大家介紹的Python 中幾種字符串格式化方法及其比較,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
相關(guān)文章
TensorFlow學(xué)習(xí)之分布式的TensorFlow運(yùn)行環(huán)境
這篇文章主要了TensorFlow學(xué)習(xí)之分布式的TensorFlow運(yùn)行環(huán)境的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02利用python生成一個(gè)導(dǎo)出數(shù)據(jù)庫的bat腳本文件的方法
下面小編就為大家?guī)硪黄胮ython生成一個(gè)導(dǎo)出數(shù)據(jù)庫的bat腳本文件的方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-12-12Python輕松獲取網(wǎng)絡(luò)時(shí)間和本地時(shí)間技巧揭秘
這篇文章主要為大家介紹了Python輕松獲取網(wǎng)絡(luò)時(shí)間和本地時(shí)間技巧揭秘,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01Python中時(shí)間datetime的處理與轉(zhuǎn)換用法總結(jié)
今天小編就為大家分享一篇關(guān)于Python中時(shí)間datetime的處理與轉(zhuǎn)換用法總結(jié),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02keras如何指定運(yùn)行時(shí)顯卡及限制GPU用量
這篇文章主要介紹了keras如何指定運(yùn)行時(shí)顯卡及限制GPU用量問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03Python報(bào)錯(cuò):NameError:?name?‘xxx‘?is?not?defined的解決辦法
這篇文章主要給大家介紹了關(guān)于Python報(bào)錯(cuò):NameError:?name?‘xxx‘?is?not?defined的解決辦法,文中通過代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-06-06