網站首頁 編程語言 正文
在Python 3.6之前,有兩種將Python表達式嵌入到字符串文本中進行格式化的主要方法:%-formatting和str.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-字符串是運行時渲染的表達式,而不是常量值。
速度比較:
'''
學習中遇到問題沒人解答?小編創建了一個Python學習交流群:711312441
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
%%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}}'
原文鏈接:https://blog.csdn.net/qdPython/article/details/127107741
相關推薦
- 2022-04-26 ASP.NET?Core?MVC中Required與BindRequired用法與區別介紹_基礎應用
- 2022-07-15 C#中Timer定時器類的簡單使用_C#教程
- 2022-12-24 Go中函數的使用細節與注意事項詳解_Golang
- 2022-08-23 Python中應用Winsorize縮尾處理的操作經驗_python
- 2022-04-02 C語言冒泡排序算法代碼詳解_C 語言
- 2021-11-18 詳解C++中inline關鍵字的作用_C 語言
- 2023-01-26 Kotlin協程Channel源碼示例淺析_Android
- 2022-12-19 批處理bat腳本獲取打包發布問題記錄_DOS/BAT
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支