溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python3中字符串格式化F-string的使用方法

發布時間:2021-06-11 15:35:41 來源:億速云 閱讀:280 作者:小新 欄目:開發技術

這篇文章給大家分享的是有關python3中字符串格式化F-string的使用方法的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

python中傳統的字符串格式化方法.

在python3.6之前,我們有兩種方式可以用來格式化字符串.

  • 占位符+%的方式

  • str.format()方法

首先復習一下這兩種方式的使用方法以及其短板.

占位符+%的方式

這種方式算是第0代字符串格式化的方法,很多語言都支持類似的字符串格式化方法. 在python的文檔中,我們也經??吹竭@種方式.

但是!!! BUT!!!

占位符+%的方式并不是python推薦的方式.

Note 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 newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.(Python3 doc)

文檔中也說了,這種方式對于元組等的顯示支持的不夠好. 而且很容易產生錯誤.

而且不符合python代碼簡潔優雅的人設...

「如何使用占位符+%的方式」

如果你接觸過其他的語言,這種方式使用起來會有一種詭異的親切感,這種親切感會讓你抓狂,內心會暗暗的罵上一句,艸,又是這德行...(這句不是翻譯,是我的個人感覺,從來都記不住那么多數據類型的關鍵字...)

In [1]: name='Eric'

In [2]: 'Hello,%s'%name

Out[2]: 'Hello,Eric'

如果要插入多個變量的話,就必須使用元組.像這樣

In [3]: name='Eric'

In [4]: age=18

In [5]: 'Hello %s,you are %d.'%(name,age)

Out[5]: 'Hello Eric,you are 18.'

「為什么說占位符+%的方式不是最好的辦法(個人認為是這種方式是一種最操蛋的操作)」

上面有少量的變量需要插入到字符串的時候,這種辦法還行. 但是一旦有很多變量需要插入到一個長字符串中...比如...

In [6]: first_name = "Eric"
 ...: last_name = "Idle"
 ...: age = 74
 ...: profession = "comedian"
 ...: affiliation = "Monty Python"


In [7]: "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)

Out[7]: 'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

像上面這個例子,代碼可讀性就很差了.(對讀和寫的人都是一種折磨...)

使用str.format()的方式

在python2.6之后,引入了str.format()函數,可以用來進行字符串的格式化. 它通過調用對象的__format__()方法(PEP3101中定義)來將對象轉化成字符串.

在str.format()方法中,通過花括號占位的方式來實現變量插入.

In [8]: 'hello,{}. You are {}.'.format(name,age)

Out[8]: 'hello,Eric. You are 74.'

甚至可以給占位符加索引.

In [9]: 'hello,{1}. You are {0}.'.format(age,name)

Out[9]: 'hello,Eric. You are 74.'

如果要在占位符中使用變量名的話,可以像下面這樣

In [10]: person={'name':'Eric','age':74}

In [11]: 'hello,{name}. you are {age}'.format(name=person['name'],age=person['age'])

Out[11]: 'hello,Eric. you are 74'

當然對于字典來說的話,我們可以使用**的小技巧.

In [15]: 'hello,{name}. you are {age}'.format(**person)

Out[15]: 'hello,Eric. you are 74'

str.format()方法對于%的方式來說已經是一種很大的提升了. 但是這并不是最好的方式.

「為什么format()方法不是最好的方式」 相比使用占位符+%的方式,format()方法的可讀性已經很高了. 但是同樣的,如果處理含有很多變量的字符串的時候,代碼會變得很冗長.

>>> first_name = "Eric"

>>> last_name = "Idle"

>>> age = 74

>>> profession = "comedian"

>>> affiliation = "Monty Python"

>>> 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.'

當然,我們也可以通過字典的方式直接傳入一個字典來解決代碼過長的問題. 但是,python3.6給我們提供了更便利的方式.

f-字符串,一種新的增強型字符串格式化方式

這種新的方式在PEP498中定義.(原文寫到這里的時候,作者可能瘋了,balabla說了一長串,冷靜的我并沒有翻譯這些廢話...) 這種方式也被叫做formatted string literals.格式化的字符串常亮...ummm...應該是這么翻譯吧...

這種方式在字符串開頭的時候,以f標識,然后通過占位符{}+變量名的方式來自動解析對象的__format__方法. 如果想了解的更加詳細,可以參考python文檔

一些簡單的例子

「使用變量名作為占位符」

In [16]: name = 'Eric'

In [17]: age=74

In [18]: f'hello {name}, you are {age}'

Out[18]: 'hello Eric, you are 74'

「這里甚至可以使用大寫的F」

In [19]: F'hello {name}, you are {age}'

Out[19]: 'hello Eric, you are 74'

你以為這就完了嗎?

不!

事情遠不止想象的那么簡單...

在花括號里甚至可以執行算數表達式

In [20]: f'{2*37}'

Out[20]: '74'

如果數學表達式都可以的話,那么在里面執行一個函數應該不算太過分吧...

In [22]: def to_lowercase(input):
 ...:  return input.lower()
 ...:

In [23]: name = 'ERIC IDLE'

In [24]: f'{to_lowercase(name)} is funny'

Out[24]: 'eric idle is funny'

你以為這就完了嗎?

不!

事情遠不止想象的那么簡單...

這玩意兒甚至可以用于重寫__str__()和__repr__()方法.

class Comedian:
 def __init__(self, first_name, last_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!"


>>> new_comedian = Comedian("Eric", "Idle", "74")

>>> f"{new_comedian}"'Eric Idle is 74.'

關于__str__()方法和__repr__()方法. 這是對象的兩個內置方法.__str()__方法用于返回一個便于人類閱讀的字符串. 而__repr__()方法返回的是一個對象的準確釋義. 這里暫時不做過多介紹. 如有必要,請關注公眾號吾碼2016(公眾號:wmcoding)并發送str_And_repr

默認情況下,f-關鍵字會調用對象的__str__()方法. 如果我們想調用對象的__repr__()方法的話,可以使用!r

>>> f"{new_comedian}"
'Eric Idle is 74.'

>>> f"{new_comedian!r}"
'Eric Idle is 74. Surprise!'

更多詳細內容可以參考這里

多個f-字符串占位符

同樣的,我們可以使用多個f-字符串占位符.

>>> name = "Eric"

>>> profession = "comedian"

>>> affiliation = "Monty Python"

>>> message = (
...  f"Hi {name}. "
...  f"You are a {profession}. "
...  f"You were in {affiliation}."
... )

>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

但是別忘了,在每一個字符串前面都要寫上f

同樣的,在字符串換行的時候,每一行也要寫上f.

>>> message = f"Hi {name}. " \
...   f"You are a {profession}. " \
...   f"You were in {affiliation}."...

>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

但是如果我們使用"""的時候,不需要每一行都寫.

>>> message = f"""
...  Hi {name}. 
...  You are a {profession}. 
...  You were in {affiliation}.
... """
...

>>> message
'\n Hi Eric.\n You are a comedian.\n You were in Monty Python.\n'

關于f-字符串的速度

f-字符串的f可能代表的含義是fast,因為f-字符串的速度比占位符+%的方式和format()函數的方式都要快.因為它是在運行時計算的表達式而不是常量值.(那為啥就快了呢...不太懂啊...)

? “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.”(PEP498)

?

(官方文檔,咱不敢翻,大意就是f-字符串是一個在運行時參與計算的表達式,而不是像常規字符串那樣是一個常量值)

在運行時,花括號內的表達式在其自己的作用域內求職,單號和字符串的部分拼接到一起,然后返回.

下面我們來看一個速度的對比.

import timeit

time1 = timeit.timeit("""name = 'Eric'\nage =74\n'%s is %s'%(name,age)""",number=100000)
time2 = timeit.timeit("""name = 'Eric'\nage =74\n'{} is {}'.format(name,age)""",number=100000)
time3 = timeit.timeit("""name = 'Eric'\nage =74\nf'{name} is {age}'""",number=100000)

從結果上看的話,f-字符串的方式速度要比其他兩種快.

0.030868000000000007
0.03721939999999996
0.0173276

f-字符串的一些細節問題

「引號的問題」 在f-字符串中,注意成對的引號使用.

f"{'Eric Idle'}"
f'{"Eric Idle"}'
f"""Eric Idle"""
f'''Eric Idle'''

以上這幾種引號方式都是支持的. 如果說我們在雙引號中需要再次使用雙引號的時候,就需要進行轉義了. f"The \"comedian\" is {name}, aged {age}."

「字典的注意事項」

在字典使用的時候,還是要注意逗號的問題.

>>> comedian = {'name': 'Eric Idle', 'age': 74}

>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."

>>> f'The comedian is {comedian['name']}, aged {comedian['age']}.'

比如上面兩條語句,第三句就是有問題的,主要還是引號引起的歧義.

「花括號」 如果字符串中想使用花括號的話,就要寫兩個花括號來進行轉義. 同理,如果想輸出兩個花括號的話,就要寫四個...

>>> f"{{74}}"'{74}'

>>> f"{{{{74}}}}"

「反斜杠」 反斜杠可以用于轉義. 但是!!!BUT!!!在f-字符串中,不允許使用反斜杠.

>>> f"{\"Eric Idle\"}"
 File "<stdin>", line 1
 f"{\"Eric Idle\"}"
      ^SyntaxError: f-string expression part cannot include a backslash

像上面這個的解決辦法就是

>>> name = "Eric Idle"

>>> f"{name}"'Eric Idle'

「行內注釋」 f-字符串表達式中不允許使用#符號.

感謝各位的閱讀!關于“python3中字符串格式化F-string的使用方法”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女