Python中格式化字串的四種實現
關於Python的格式化字串,幾乎所有接觸過Python語言的人都知道其中一種,即使用運算子%,但對於絕大多數初學者來說也僅此而已。
因此,本文將先總結如何通過%運算子來格式化字串,同時指出這種方式的缺點,然後帶你瞭解Python中另外三種強大的格式化字串的方式:str.format()、f-string以及模板字串,並給出在何時選擇何種方式的建議。
一、%運算子格式化字串
1. 如何使用
字串物件都有一個使用%運算子完成的內建操作,可被用來格式化字串。最簡單的如:
In [11]: name = "Monty Python" In [12]: "Hello,%s." % name Out[12]: 'Hello,Monty Python.'
如果想要對一段字串中插入多個變數進行格式化,則需要使用一個元組將待插入變數包在一起,如:
In [14]: name = "Monty Python" In [15]: age = 100 In [16]: "Hello,%s. You are %d years old" % (name,age) Out[16]: 'Hello,Monty Python. You are 100 years old'
2. 缺點概述
使用%運算子的方式來格式化字串自Python語言誕生之日起就已存在,上述程式碼看起來也很直觀易讀,但是當字串更長,待插入變數更多,則使用%來格式化字串的可讀性將急劇下降,如:
In [23]: first_name = "Eric" In [24]: last_name = "Idle" In [25]: age = 100 In [26]: profession = "comedian" In [27]: affiliation = "Monty Python" In [28]: "Hello,%s %s. You are %s. You are a %s. You were a member of %s." % (first_name,last_name,age,profession,affiliation) Out[28]: 'Hello,Eric Idle. You are 100. You are a comedian. You were a member of Monty Python.'
上述使用%格式化字串不僅冗長,而且容易出錯,因為這種方式並不夠正確顯示元組或者字典。
實際上,在Python官方文件中,對於使用%運算子格式化字串這種方式的評價也是負面的:
- The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly).使用%格式化字串會產生一系列異常,這些異常將引起一系列常見錯誤(如:無法正確顯示元組和字典)。
- Using the newerformatted string literals,the str.format() interface,ortemplate strings may help avoid these errors.
- 使用更新的格式化字串字面量(f-string:formatted string literals),str.format()介面或者模板字串(template strings)可以幫助避免這些錯誤。
Each of these alternatives provides their own trade-offs and benefits of simplicity,flexibility,and/or extensibility.
當然,上述三種可替代的格式化字串方式也都在簡潔、靈活和可擴充套件方面有所取捨。
二、str.format()格式化字串
1. 如何使用
str.format()是對使用%實現格式化字串的一種改進。這種方式使用的語法和普通函式呼叫相差無幾。
使用str.format(),字串中待替換的域使用{}表示:
In [29]: name = "Eric" In [30]: age = 100 In [31]: "Hello,{}. You are {}.".format(name,age) Out[31]: 'Hello,Eric. You are 100.'
也可以通過索引的方式指定format()中哪一個變數和值應該填入哪一個{},如:
In [32]: name = "Eric" In [33]: age = 100 In [34]: "Hello,{1}. You are {0}.".format(age,name) Out[34]: 'Hello,Eric. You are 100.'
除了索引,也可以通過在{}中指定名稱的方式來實現類似上述功能,如:
In [36]: name = "Eric" In [37]: age = 100 In [38]: "Hello,{name}. You are {age}.".format(age=age,name=name) Out[38]: 'Hello,Eric. You are 100.'
基於上面的方式,當待格式化的資訊都來自一個字典時,Python中還有如下騷操作:
In [39]: person = {'name': 'Eric','age': 100} In [40]: "Hello,{name}. You are {age}.".format(name=person['name'],age=person['age']) Out[40]: 'Hello,Eric. You are 100.'
更騷的是,上面的騷操作還能利用字典拆包**進一步簡化:
In [41]: person = {'name': 'Eric','age': 100} In [42]: "Hello,{name}. You are {age}.".format(**person) Out[42]: 'Hello,Eric. You are 100.'
2. 缺點概述
相較於%運算子方式,使用str.format()已經使得格式化字串語法更加可讀,但是當變數增多時,這種方式寫出的程式也會顯得很冗長:
In [43]: first_name = "Eric" In [44]: last_name = "Idle" In [45]: age = 74 In [46]: profession = "comedian" In [47]: affiliation = "Monty Python" In [48]: print(("Hello,{first_name} {last_name}. You are {age}. " + ...: "You are a {profession}. You were a member of {affiliation}.") \ ...: .format(first_name=first_name,last_name=last_name,age=age,\ ...: profession=profession,affiliation=affiliation)) Hello,Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.
三、f-string格式化字串
在Python 3.6中f-string被引入(具體請見PEP 498),也被稱作格式化字串字面量(formatted string literals)。
f-string是字串字面量,且其以字母f開頭,{}中包含變數或表示式,變數或表示式將在執行(runtime)時通過使用__format__協議被替換成具體的值。
1. 如何使用
簡單的f-string格式化字串如:
In [49]: name = "Eric" In [50]: age = 100 In [51]: f"Hello,{name}. You are {age}." Out[51]: 'Hello,Eric. You are 100.'
如前所述,{}中除接受變數外,還接受表示式,如:
In [52]: f"{2 * 37}" Out[52]: '74'
f-string更強大的地方在於,{}中接受函式呼叫:
In [53]: def to_lowercase(input): ...: return input.lower() ...: In [54]: name = "Eric Idle" In [55]: f"{to_lowercase(name)} is funny." Out[55]: 'eric idle is funny.'
甚至,你可以對創建於類的物件使用f-string,如:
class Comedian: def __init__(self,first_name,age): self.first_name = first_name self.last_name = last_name self.age = age def __str__(self): return f"{self.first_name} {self.last_name} is {self.age}." def __repr__(self): return f"{self.first_name} {self.last_name} is {self.age}. Surprise!" def main(): new_comedian = Comedian("Eric","Idle","74") print(f"{new_comedian}") if __name__ == '__main__': main()
上述程式碼的輸出為:
Eric Idle is 74.
四、Template類格式化字串
https://www.jb51.net/article/155119.htm
五、參考資料
[1] Python 3's f-Strings: An Improved String Formatting Syntax (Guide)
[2] Python String Formatting Best Practices
到此這篇關於Python中格式化字串的四種實現的文章就介紹到這了,更多相關Python格式化字串內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!