Strings are present throughout Python codebases. They’re used for rendering messages in user interfaces and command-line utilities. They’re used for writing data to files and sockets. They’re used for specifying what’s gone wrong in Exception details (see Item 27: “Use Comprehensions Instead of map and filter”). They’re used in debugging (see Item 80: “Consider Interactive Debugging with pdb” and Item 75: “Use repr Strings for Debugging Output”).
字符串存在于整個(gè)Python代碼庫(kù)中。它們用于在用戶界面和命令行工具中呈現(xiàn)消息,它們用于將數(shù)據(jù)寫入文件和套接字接口,它們用于指定異常詳細(xì)信息中的錯(cuò)誤(參見第27項(xiàng):“使用推導(dǎo)式代替map和filter”),它們用于調(diào)試(參見第80項(xiàng):“考慮使用pdb進(jìn)行交互調(diào)試”和第75項(xiàng):“使用repr字符串進(jìn)行調(diào)試輸出”)。
Formatting is the process of combining predefined text with data values into a single human-readable message that’s stored as a string. Python has four different ways of formatting strings that are built into the language and standard library. All but one of them, which is covered last in this item, have serious shortcomings that you should understand and avoid.
格式化是將預(yù)定義的文本與數(shù)據(jù)值組合的過程,它以人類可讀的字符串形式進(jìn)行存儲(chǔ)。Python有四種不同的格式化字符串的方法,這些方法都內(nèi)置在語(yǔ)言和標(biāo)準(zhǔn)庫(kù)中。除了本章節(jié)最后介紹的方法之外,其他方法都有嚴(yán)重的缺陷,你應(yīng)該了解并避免使用它們。
The most common way to format a string in Python is by using the % formatting operator. The predefined text template is provided on the left side of the operator in a format string. The values to insert into the template are provided as a single value or tuple of multiple values on the right side of the format operator. For example, here I use the % operator to convert difficult-to-read binary and hexadecimal values to integer strings:
在Python中格式化字符串最常見的方法是使用 % 格式化操作符。預(yù)定義的文本模板在操作符的左側(cè),它以格式字符串的形式提供。要插入到模板中的值在%右側(cè),以單個(gè)值或多個(gè)值的元組的形式提供。例如,這里我使用%操作符將晦澀的二進(jìn)制和十六進(jìn)制值轉(zhuǎn)換為整型字符串:
b = 0xc5f
print('Binary is %d, hex is %d' % (a, b))
>>>
Binary is 187, hex is 3167
The format string uses format specifiers (like %d) as placeholders that will be replaced by values from the right side of the formatting expression. The syntax for format specifiers comes from C’s printf function, which has been inherited by Python (as well as by other programming languages). Python supports all the usual options you’d expect from printf, such as %s, %x, and %f format specifiers, as well as control over decimal places, padding, fill, and alignment. Many programmers who are new to Python start with C-style format strings because they’re familiar and simple to use.
格式字符串使用格式說明符(如%d)作為占位符,這些占位符將被格式表達(dá)式右側(cè)的值替換。格式說明符的語(yǔ)法來(lái)自C語(yǔ)言的printf函數(shù),該函數(shù)已被Python(以及其他編程語(yǔ)言)繼承。Python支持printf中所有常見的選項(xiàng),如%s、%x和%f格式說明符,以及對(duì)小數(shù)位數(shù)、填補(bǔ)、填充和對(duì)齊的控制。許多新Python程序員從C風(fēng)格的格式字符串開始,因?yàn)樗麄兪煜で乙子谑褂谩?/p>
There are four problems with C-style format strings in Python.
在Python中使用C風(fēng)格的格式字符串有四個(gè)問題。
The first problem is that if you change the type or order of data values in the tuple on the right side of a formatting expression, you can get errors due to type conversion incompatibility. For example, this simple formatting expression works:
第一個(gè)問題是,如果更改格式化表達(dá)式右側(cè)元組中數(shù)據(jù)值的類型或順序,可能會(huì)由于類型轉(zhuǎn)換不兼容而出現(xiàn)錯(cuò)誤。例如,下面這個(gè)簡(jiǎn)單的格式化表達(dá)式可以正常運(yùn)行:
key = 'my_var'
value = 1.234
formatted = '%-10s = %.2f' % (key, value)
print(formatted)
>>>
my_var = 1.23
But if you swap key and value, you get an exception at runtime:
但是如果你交換鍵和值,你會(huì)在運(yùn)行時(shí)得到一個(gè)異常:
reordered_tuple = '%-10s = %.2f ' % (value, key)
>>>
Traceback ...
TypeError: must be real number, not str
Similarly, leaving the right side parameters in the original order but changing the format string results in the same error:
類似地,讓右邊的參數(shù)保持原來(lái)的順序,但更改格式字符串也會(huì)導(dǎo)致相同的錯(cuò)誤:
reordered_string = '%.2f = %-10s ' % (key, value)
>>>
Traceback ...
TypeError: must be real number, not str
To avoid this gotcha, you need to constantly check that the two sides of the % operator are in sync; this process is error prone because it must be done manually for every change.
為了避免這個(gè)問題,你需要不斷地檢查%操作符的兩邊是否同步; 這個(gè)過程很容易出錯(cuò),因?yàn)槊看胃亩急仨毷謩?dòng)執(zhí)行。
The second problem with C-style formatting expressions is that they become difficult to read when you need to make small modifications to values before formatting them into a string—and this is an extremely common need. Here, I list the contents of my kitchen pantry without making inline changes:
C風(fēng)格格式化表達(dá)式的第二個(gè)問題是: 當(dāng)您需要在格式化字符串之前對(duì)值進(jìn)行小的修改時(shí),這將導(dǎo)致代碼變得難以閱讀,而這種小的修改又是非常常見的需求。在這里,我列出了我的廚房食品儲(chǔ)藏室的內(nèi)容,而沒有做內(nèi)聯(lián)更改:
pantry = [
( 'avocados ', 1.25),
( 'bananas ', 2.5),
( 'cherries ', 15),
]
for i, (item, count) in enumerate (pantry):
print ( '#%d: %-10s = %.2f ' % (i, item, count))
>>>
#0: avocados = 1.25
#1: bananas = 2.50
#2: cherries = 15.00
Now, I make a few modifications to the values that I’m formatting to make the printed message more useful. This causes the tuple in the formatting expression to become so long that it needs to be split across multiple lines, which hurts readability:
現(xiàn)在,為了使打印信息更實(shí)用,我對(duì)正在格式化的值做了一些修改。這導(dǎo)致了格式化表達(dá)式中的元組變得太長(zhǎng),以至于需要將其拆分為多行,而這就損害了可讀性:
for i, (item, count) in enumerate (pantry):
print ( '#%d: %-10s = %d ' % (
i + 1,
item.title (),
round (count)))
>>>
#1: Avocados = 1
#2: Bananas = 2
#3: Cherries = 15
The third problem with formatting expressions is that if you want to use the same value in a format string multiple times, you have to repeat it in the right side tuple:
格式化表達(dá)式的第三個(gè)問題是,如果你想在格式化字符串中多次使用相同的值,你必須在右邊的元組中重復(fù)它:
template = '%s loves food. See %s cook. '
name = 'Max '
formatted = template % (name, name)
print (formatted)
>>>
Max loves food. See Max cook.
This is especially annoying and error prone if you have to repeat small modifications to the values being formatted. For example, here I remembered to call the title () method multiple times, but I could have easily added the method call to one reference to name and not the other, which would cause mismatched output:
如果您必須對(duì)被格式化的值進(jìn)行重復(fù)的小修改,這尤其令人討厭而且容易出錯(cuò)。例如,這里我記得多次調(diào)用title()方法,但是我可能很容易地將方法調(diào)用添加到其中一個(gè)name的引用,而卻忘記了另外一個(gè),這會(huì)導(dǎo)致不匹配的輸出:
name = 'brad '
formatted = template % (name.title (), name.title ())
print (formatted)
>>>
Brad loves food. See Brad cook.
To help solve some of these problems, the % operator in Python has the ability to also do formatting with a dictionary instead of a tuple. The keys from the dictionary are matched with format specifiers with the corresponding name, such as %(key)s. Here, I use this functionality to change the order of values on the right side of the formatting expression with no effect on the output, thus solving problem #1 from above:
為了幫助解決其中一些問題,Python中的%操作符還能夠使用字典而不是元組進(jìn)行格式化。字典中的鍵與具有相應(yīng)名稱的格式說明符匹配,例如%(key)s。在這里,我使用這個(gè)功能來(lái)改變格式化表達(dá)式右側(cè)值的順序,而不會(huì)影響輸出,從而解決了上面的問題#1:
key = 'my_var '
value = 1.234
old_way = '%-10s = %.2f ' % (key, value)
new_way = '% (key)-10s = % (value).2f ' % { 'key ': key, 'value ': value} # Original
reordered = '% (key)-10s = % (value).2f ' % { 'value ': value, 'key ': key} # Swapped
assert old_way == new_way == reordered
Using dictionaries in formatting expressions also solves problem #3 from above by allowing multiple format specifiers to reference the same value, thus making it unnecessary to supply that value more than once:
在格式化表達(dá)式中使用字典還解決了上面的問題#3,它允許多個(gè)格式說明符引用相同的值,從而無(wú)需多次提供該值:
name = 'Max '
template = '%s loves food. See %s cook. '
before = template % (name, name) # Tuple
template = '% (name)s loves food. See % (name)s cook. '
after = template % { 'name ': name} # Dictionary
assert before == after
However, dictionary format strings introduce and exacerbate other issues. For problem #2 above, regarding small modifications to values before formatting them, formatting expressions become longer and more visually noisy because of the presence of the dictionary key and colon operator on the right side. Here, I render the same string with and without dictionaries to show this problem:
然而,字典格式字符串引入,加劇了其他問題。對(duì)于上面的問題#2,如果在格式化之前對(duì)值進(jìn)行的小修改,格式化表達(dá)式將會(huì)變得更長(zhǎng),視覺效果會(huì)更加嘈雜,因?yàn)樵谟疫叧霈F(xiàn)了字典鍵和冒號(hào)操作符。這里,我使用有字典和沒有字典兩種方式,渲染相同的字符串來(lái)說明這個(gè)問題:
for i, (item, count) in enumerate (pantry):
before = '#%d: %-10s = %d ' % (
i + 1,
item.title (),
round (count))
after = '#% (loop)d: % (item)-10s = % (count)d ' % {
'loop ': i + 1,
'item': item.title (),
'count ': round (count),
}
assert before == after
Using dictionaries in formatting expressions also increases verbosity, which is problem #4 with C-style formatting expressions in Python. Each key must be specified at least twice—once in the format specifier, once in the dictionary as a key, and potentially once more for the variable name that contains the dictionary value:
在格式化表達(dá)式中使用字典還會(huì)增加冗長(zhǎng),這就是Python中使用C風(fēng)格格式化表達(dá)式帶來(lái)的問題#4。每個(gè)鍵必須至少指定兩次——一次在格式說明符中,一次在字典中作為鍵,可能還要為包含字典值的變量名指定一次:
soup = 'lentil '
formatted = 'Today\ 's soup is % (soup)s. ' % { 'soup ': soup}
print (formatted)
>>>
Today 's soup is lentil.
Besides the duplicative characters, this redundancy causes formatting expressions that use dictionaries to be long. These expressions often must span multiple lines, with the format strings being concatenated across multiple lines and the dictionary assignments having one line per value to use in formatting:
除了重復(fù)字符之外,這種冗余還導(dǎo)致使用字典的格式表達(dá)式很長(zhǎng)。這些表達(dá)式通常必須跨越多行,格式字符串跨多行連接,并且字典賦值在格式化中時(shí)每個(gè)值使用一行:
menu = {
'soup ': 'lentil ',
'oyster ': 'kumamoto ',
'special ': 'schnitzel ',
}
template = ('Today\ 's soup is % (soup)s, '
'buy one get two % (oyster)s oysters, '
'and our special entrée is % (special)s. ')
formatted = template % menu
print (formatted)
>>>
Today 's soup is lentil, buy one get two kumamoto oysters, and our special entrée is schnitzel.
To understand what this formatting expression is going to produce, your eyes have to keep going back and forth between the lines of the format string and the lines of the dictionary. This disconnect makes it hard to spot bugs, and readability gets even worse if you need to make small modifications to any of the values before formatting.
為了理解這個(gè)格式化表達(dá)式將產(chǎn)生什么結(jié)果,您的眼睛必須在格式字符串的行和字典的行之間來(lái)回切換。這種脫節(jié)使得很難發(fā)現(xiàn)bug,而且如果你需要在格式化之前對(duì)任何值進(jìn)行小的修改,可讀性就會(huì)變得更加糟糕。
There must be a better way.
一定有一種更好的方法。
The format Built-in and str.format
內(nèi)置的format方法和str.format
Python 3 added support for advanced string formatting that is more expressive than the old C-style format strings that use the % operator. For individual Python values, this new functionality can be accessed through the format built-in function. For example, here I use some of the new options ( , for thousands separators and ^ for centering) to format values:
Python 3增加了對(duì)高級(jí)字符串格式化的支持,這種格式比使用%操作符的舊C風(fēng)格格式字符串更具表現(xiàn)力。對(duì)于單個(gè)Python值,這個(gè)新功能可以通過format內(nèi)置函數(shù)訪問。例如,這里我使用了一些新的選項(xiàng)(, 千分隔符和 ^居中操作符)來(lái)格式化值:
a = 1234.5678
formatted = format (a, ',.2f ')
print (formatted)
b = 'my string '
formatted = format (b, '^20s ')
print ( '* ', formatted, '* ')
>>>
1,234.57
* my string *
You can use this functionality to format multiple values together by calling the new format method of the str type. Instead of using C-style format specifiers like %d, you can specify placeholders with {}. By default the placeholders in the format string are replaced by the corresponding positional arguments passed to the format method in the order in which they appear:
您可以使用此功能通過調(diào)用str類型的新format方法來(lái)同時(shí)格式化多個(gè)值??梢允褂脅}指定占位符,而不是使用c風(fēng)格的格式說明符%d。默認(rèn)情況下,format字符串中的占位符會(huì)被傳遞給format方法的相應(yīng)位置參數(shù)替換,位置參數(shù)的出現(xiàn)順序如下:
key = 'my_var '
value = 1.234
formatted = '{} = {} '.format (key, value)
print (formatted)
>>>
my_var = 1.234
Within each placeholder you can optionally provide a colon character followed by format specifiers to customize how values will be converted into strings (see help ( 'FORMATTING ') for the full range of options) :
在每個(gè)占位符中,你可以選擇提供一個(gè)冒號(hào)字符,后面跟上格式說明符來(lái)定制如何將值轉(zhuǎn)換為字符串(請(qǐng)參閱help ('FORMATTING ')了解所有選項(xiàng)):
formatted = '{:<10} = {:.2f} '.format (key, value)
print (formatted)
>>>
my_var = 1.23
The way to think about how this works is that the format specifiers will be passed to the format built-in function along with the value (format (value, '.2f ') in the example above). The result of that function call is what replaces the placeholder in the overall formatted string. The formatting behavior can be customized per class using the format special method.
理解這是如何運(yùn)行的: 格式說明符將與值(上面示例中的format(value,'.2f'))一起傳遞給format內(nèi)置函數(shù)。該函數(shù)調(diào)用的結(jié)果將替換整個(gè)格式化字符串中的占位符。格式化行為可以使用format特殊方法為每個(gè)類定制。
With C-style format strings, you need to escape the % character (by doubling it) so it’s not interpreted as a placeholder accidentally. With the str.format method you need to similarly escape braces:
對(duì)于C風(fēng)格的格式字符串,您需要轉(zhuǎn)義%字符(通過將其加倍),以便它不會(huì)意外地被解釋為一個(gè)占位符。對(duì)于str.format方法,你需要類似地轉(zhuǎn)義花括號(hào):
print ( '%.2f%% ' % 12.5)
print ( '{} replaces {{}} '.format (1.23))
>>>
12.50%
1.23 replaces {}
Within the braces you may also specify the positional index of an argument passed to the format method to use for replacing the placeholder. This allows the format string to be updated to reorder the output without requiring you to also change the right side of the formatting expression, thus addressing problem #1 from above: *
在花括號(hào)中,您還可以指定傳遞給format方法的參數(shù)的位置索引,以用于替換占位符。這允許更新格式字符串來(lái)重新排序輸出,而不需要您更改格式表達(dá)式的右側(cè)的順序,從而解決上面的問題#1:
formatted = '{1} = {0} '.format (key, value)
print (formatted)
>>> 1.234 = my_var
The same positional index may also be referenced multiple times in the format string without the need to pass the value to the format method more than once, which solves problem #3 from above:
同樣的位置索引也可以在format字符串中被引用多次,而不需要將值多次傳遞給format方法,這解決了上面的問題#3:
formatted = '{0} loves food. See {0} cook. '.format (name)
print (formatted)
>>>
Max loves food. See Max cook.
Unfortunately, the new format method does nothing to address problem #2 from above, leaving your code difficult to read when you need to make small modifications to values before formatting them. There’s little difference in readability between the old and new options, which are similarly noisy:
不幸的是,新的format方法沒有解決上面的第2個(gè)問題,當(dāng)您需要在格式化值之前對(duì)其進(jìn)行小的修改時(shí),代碼依然很難閱讀。新舊選項(xiàng)在可讀性上幾乎沒有差別,視覺上同樣很嘈雜:
for i, (item, count) in enumerate (pantry):
old_style = '#%d: %-10s = %d ' % (
i + 1,
item.title (),
round (count))
new_style = '#{}: {:<10s} = {} '.format (
i + 1,
item.title (),
round (count))
assert old_style == new_style
There are even more advanced options for the specifiers used with the str.format method, such as using combinations of dictionary keys and list indexes in placeholders, and coercing values to Unicode and repr strings:
對(duì)于str.format方法使用的說明符,甚至還有更高級(jí)的選項(xiàng),比如在占位符中使用字典鍵和列表索引的組合,以及將值強(qiáng)制為Unicode和repr字符串:
formatted = 'First letter is {menu [oyster] [0] !r} '.format (menu=menu)
print (formatted)
>>>
First letter is 'k '
But these features don’t help reduce the redundancy of repeated keys from problem #4 above. For example, here I compare the verbosity of using dictionaries in C-style formatting expressions to the new style of passing keyword arguments to the format method:
但是這些特性并不能幫助減少上面問題4中重復(fù)鍵的冗余。例如,在這里,我比較了兩種風(fēng)格的冗長(zhǎng)性,一種是在表達(dá)式中使用字典的C風(fēng)格格式化,另一種是向format方法傳遞關(guān)鍵字參數(shù)的新風(fēng)格:
old_template = (
'Today\ 's soup is % (soup)s, '
'buy one get two % (oyster)s oysters, '
'and our special entrée is % (special)s. ')
old_formatted = template % {
'soup ': 'lentil ',
'oyster ': 'kumamoto ',
'special ': 'schnitzel ',
}
new_template = (
'Today\ 's soup is {soup}, '
'buy one get two {oyster} oysters, '
'and our special entrée is {special}. ')
new_formatted = new_template.format (
soup= 'lentil ',
oyster= 'kumamoto ',
special= 'schnitzel ',
)
assert old_formatted == new_formatted
This style is slightly less noisy because it eliminates some quotes in the dictionary and a few characters in the format specifiers, but it’s hardly compelling.
這種風(fēng)格稍微不那么嘈雜,因?yàn)樗俗值渲械囊恍┮?hào)和格式說明符中的一些字符,但它很難引人注目。
Further, the advanced features of using dictionary keys and indexes within placeholders only provides a tiny subset of Python’s expression functionality. This lack of expressiveness is so limiting that it undermines the value of the format method from str overall.
此外,在占位符中使用字典鍵和索引的高級(jí)特性只提供了Python表達(dá)式功能的一小部分。這種表達(dá)性的缺乏是如此的有限,以至于它從整體上破壞了str的format方法的價(jià)值。
Given these shortcomings and the problems from C-style formatting expressions that remain (problems #2 and #4 from above), I suggest that you avoid the str.format method in general.
鑒于這些缺點(diǎn)和C風(fēng)格格式表達(dá)式仍然存在的問題(上面的問題#2和#4),我建議您一般避免使用str.format方法。
It’s important to know about the new mini language used in format specifiers (everything after the colon) and how to use the format built-in function. But the rest of the str.format method should be treated as a historical artifact to help you understand how Python’s new f-strings work and why they’re so great.
了解格式說明符(冒號(hào)之后的所有內(nèi)容)中使用的新迷你語(yǔ)言,以及如何使用format內(nèi)置函數(shù)非常重要。但是str.format方法的其余部分應(yīng)該被視為歷史文物,以幫助您理解Python的新的f-strings是如何工作的,以及它們?yōu)槭裁慈绱藗ゴ蟆?/p>
Interpolated Format Strings
插值格式字符串
Python 3.6 added interpolated format strings—f-strings for short—to solve these issues once and for all. This new language syntax requires you to prefix format strings with an f character, which is similar to how byte strings are prefixed with a b character and raw (unescaped) strings are prefixed with an r character.
Python3.6添加了插值格式字符串——簡(jiǎn)稱f-string——來(lái)一勞永逸地解決這些問題。這種新的語(yǔ)法要求您在格式字符串前加上f字符,這類似于字節(jié)字符串前綴為b字符,原始(未轉(zhuǎn)義)字符串前綴為r字符。
F-strings take the expressiveness of format strings to the extreme, solving problem #4 from above by completely eliminating the redundancy of providing keys and values to be formatted. They achieve this pithiness by allowing you to reference all names in the current Python scope as part of a formatting expression:
f-string將格式字符串的表達(dá)能力發(fā)揮到了極致,它通過完全消除格式化時(shí)的鍵和值的冗余,解決了上面的問題#4。它通過允許你引用當(dāng)前Python作用域中的所有名稱作為格式化表達(dá)式的一部分來(lái)實(shí)現(xiàn)這種簡(jiǎn)潔:
key = 'my_var '
value = 1.234
formatted = f '{key} = {value} '
print (formatted)
>>>
my_var = 1.234
All of the same options from the new format built-in mini language are available after the colon in the placeholders within an f-string, as is the ability to coerce values to Unicode and repr strings similar to the str.format method:
新format內(nèi)置迷你語(yǔ)言中的所有相同選項(xiàng)都可以在f-string占位符中的冒號(hào)之后使用,就像將值強(qiáng)制轉(zhuǎn)換為Unicode和repr字符串的能力一樣,類似于str.format方法:
formatted = f '{key !r:<10} = {value:.2f} '
print (formatted)
>>>
'my_var ' = 1.23
Formatting with f-strings is shorter than using C-style format strings with the % operator and the str.format method in all cases. Here, I show all these options together in order of shortest to longest, and line up the left side of the assignment so you can easily compare them:
在任何情況下,使用f-string進(jìn)行格式化都比使用C風(fēng)格的%操作符和str.format方法的更短。在這里,我將所有這些選項(xiàng)按最短到最長(zhǎng)的順序排列在一起,并將賦值的左側(cè)對(duì)齊,這樣你就可以輕松地比較它們:
f_string = f '{key:<10} = {value:.2f} '
c_tuple = '%-10s = %.2f ' % (key, value)
str_args = '{:<10} = {:.2f} '.format (key, value)
str_kw = '{key:<10} = {value:.2f} '.format (key=key, value=value)
c_dict = '% (key)-10s = % (value).2f ' % { 'key ': key, 'value ': value}
assert c_tuple == c_dict == f_string
assert str_args == str_kw == f_string
F-strings also enable you to put a full Python expression within the placeholder braces, solving problem #2 from above by allowing small modifications to the values being formatted with concise syntax. What took multiple lines with C-style formatting and the str.format method now easily fits on a single line:
f-string還允許您將一個(gè)完整的Python表達(dá)式放入占位符大括號(hào)中,通過允許使用簡(jiǎn)潔語(yǔ)法對(duì)格式化的值進(jìn)行小的修改,解決了上面的問題#2。使用C風(fēng)格格式化的多行代碼和str.format方法現(xiàn)在可以輕松地適用于單行:
for i, (item, count) in enumerate (pantry):
old_style = '#%d: %-10s = %d ' % (
i + 1,
item.title (),
round (count))
new_style = '#{}: {:<10s} = {} '.format (
i + 1,
item.title (),
round (count))
f_string = f '#{i+1}: {item.title ():<10s} = {round (count)} '
assert old_style == new_style == f_string
Or, if it’s clearer, you can split an f-string over multiple lines by relying on adjacent-string concatenation (similar to C). Even though this is longer than the single-line version, it’s still much clearer than any of the other multiline approaches:
或者,如果你想讓它更清晰,你可以通過依賴鄰接字符串拼接(類似于C)的方式將一個(gè)f-string拆分為多行。盡管這比單行版本要長(zhǎng),但它仍然比任何其他多行方法更清晰:
for i, (item, count) in enumerate (pantry):
print (f '#{i+1}: '
f '{item.title ():<10s} = '
f '{round (count)} ')
>>>
#1: Avocados = 1
#2: Bananas = 2
#3: Cherries = 15
Python expressions may also appear within the format specifier options. For example, here I parameterize the number of digits to print by using a variable instead of hard-coding it in the format string:
Python表達(dá)式也可以出現(xiàn)在格式說明符選項(xiàng)中。例如,這里我通過使用變量而不是在格式字符串中硬編碼來(lái)參數(shù)化要打印的數(shù)字:
places = 3
number = 1.23456
print (f'My number is {number:.{places}f} ')
>>>
My number is 1.235
The combination of expressiveness, terseness, and clarity provided by f-strings makes them the best built-in option for Python programmers. Any time you find yourself needing to format values into strings, choose f-strings over the alternatives.
f-string所提供的表達(dá)性、簡(jiǎn)潔性和清晰度的組合使其成為Python程序員的最佳內(nèi)置選項(xiàng)。任何時(shí)候,當(dāng)您發(fā)現(xiàn)需要將值格式化為字符串時(shí),請(qǐng)選擇f-string代替其他任何選項(xiàng)。
Things to Remember
要記住的事
? C-style format strings that use the % operator suffer from a variety of gotchas and verbosity problems.
? The str.format method introduces some useful concepts in its formatting specifiers mini language, but it otherwise repeats the mistakes of C-style format strings and should be avoided.
? F-strings are a new syntax for formatting values into strings that solves the biggest problems with C-style format strings.
? F-strings are succinct yet powerful because they allow for arbitrary Python expressions to be directly embedded within format specifiers.
? 使用%操作符的C風(fēng)格字符串有各種陷阱和冗長(zhǎng)的問題。
? str.format方法在其格式說明符迷你語(yǔ)言中引入了一些有用的概念,但它重復(fù)了C風(fēng)格格式字符串的錯(cuò)誤,應(yīng)該避免。
? F-strings是一種將值格式化為字符串的新語(yǔ)法,解決了C風(fēng)格格式字符串的最大問題。
? F-strings簡(jiǎn)潔而強(qiáng)大,因?yàn)樗鼈冊(cè)试S任意的Python表達(dá)式直接嵌入格式說明符。