Python3 格式化字符串


Python3 格式化字符串

在Python 3.6之前,有兩種將Python表達式嵌入到字符串文本中進行格式化的主要方法:%-formattingstr.format()

一、%-formatting

name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)

注:這種格式不是很好,因為它是冗長的,會導致錯誤。

二、str.format()

str.format() 在Python 2.6中引入的。

(1)使用str.format(),替換字段用大括號標記:

"Hello, {}. You are {}.".format(name, age)
# 輸出結果:'Hello, Eric. You are 74.'

(2)可以通過引用其索引來以任何順序引用變量:

"Hello, {1}. You are {0}-{0}.".format(age, name)
# 輸出結果:'Hello, Eric. You are 74-74.'

(3)如果插入變量名稱,則會獲得額外的能夠傳遞對象的權限,然后在大括號之間引用參數和方法:

person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
# 輸出結果:'Hello, Eric. You are 74.'

(4)可以使用**來用字典來完成這個巧妙的技巧:

person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(**person)
# 輸出結果:'Hello, Eric. You are 74.'

注:當處理多個參數和更長的字符串時,str.format()仍然可能非常冗長。

三、f-Strings

f-Strings是在Python 3.6開始加入標准庫。也稱為“格式化字符串文字”,F字符串是開頭有一個f的字符串文字,以及包含表達式的大括號將被其值替換。

(1)f-Strings

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
# 輸出結果:'Hello, Eric. You are 74.'

(2)用大寫字母F也是有效的:

name = "Eric"
age = 74
F"Hello, {name}. You are {age}."
# 輸出結果:'Hello, Eric. You are 74.'

(3)可以調用函數

name = "Eric"
age = 74
f"{name.lower()} is funny."
# 輸出結果:'eric is funny.'

f"{2 * 37}"
# 輸出結果:'74'

(4)可以使用帶有f字符串的類創建對象

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

f"{new_comedian!r}"
# 輸出結果:'Eric Idle is 74. Surprise!'

(5)多行f-string

message = (f"Hi {name}. "
        f"You are a {profession}. "
        f"You were in {affiliation}.")
# 輸出結果:'Hi Eric. You are a comedian. You were in Monty Python.'

message = (f"Hi {name}. "
        "You are a {profession}. "
        "You were in {affiliation}.")
# 輸出結果:'Hi Eric. You are a {profession}. You were in {affiliation}.'

(6)使用"""

message = f"""
    Hi {name}. 
    You are a {profession}. 
    You were in {affiliation}.
 """
# 輸出結果:'\n    Hi Eric. \n    You are a comedian. \n    You were in Monty Python.\n '

(7)性能

f字符串中的f也可以代表“速度快”。f-字符串是運行時渲染的表達式,而不是常量值。

速度比較:

%%timeit
name = "Eric" 
age = 74 
'%s is %s.' % (name, age)
# 202 ns ± 2.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
name = "Eric" 
age = 74 
'{} is {}.'.format(name, age)
# 244 ns ± 5.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
name = "Eric" 
age = 74 
'{name} is {age}.'
# 14.4 ns ± 0.0121 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

(8)語法正確格式

f"{'Eric Idle'}"
# 輸出結果:'Eric Idle'
f'{"Eric Idle"}'
# 輸出結果:'Eric Idle'
f"""Eric Idle"""
# 輸出結果:'Eric Idle'
f'''Eric Idle'''
# 輸出結果:'Eric Idle'
f"The \"comedian<span class="string">" is {name}, aged {age}."
# 輸出結果:'The "comedian" is Eric, aged 74.'

(9)字典

字典的鍵使用單引號,請記住確保對包含鍵的f字符串使用雙引號。

comedian = {'name': 'Eric Idle', 'age': 74}
f"The comedian is {comedian['name']}, aged {comedian['age']}."
# 輸出結果:'The comedian is Eric Idle, aged 74.'

(10)大括號

為了使字符串出現大括號,您必須使用雙大括號:

f"{{74}}"
# 輸出結果:'{74}'

f"{{{{74}}}}"
# 輸出結果:'{{74}}'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM