Python - 格式化 - 字串
字串格式化
正如我們在 Python 變數章節中所學,我們不能這樣組合字串和數字:
示例
age = 36
txt = "My name is John, I am " + age
print(txt)
自己動手試一試 »
但我們可以透過使用f-string 或 format()
方法來組合字串和數字!
F-Strings
F-String 是在 Python 3.6 中引入的,現在是格式化字串的首選方式。
要將字串指定為 f-string,只需在字串文字前加上一個 f
,然後新增花括號 {}
作為變數和其他操作的佔位符。
示例
建立 f-string
age = 36
txt = f"My name is John, I am {age}"
print(txt)
自己動手試一試 »
佔位符和修飾符
佔位符可以包含變數、操作、函式和修飾符來格式化值。
示例
為 price
變數新增佔位符
price = 59
txt = f"The price is {price} dollars"
print(txt)
自己動手試一試 »
佔位符可以包含一個修飾符來格式化值。
透過新增冒號 :
後跟一個合法的格式化型別來包含修飾符,例如 .2f
,表示小數點後兩位固定點數。
示例
顯示價格,保留兩位小數
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
自己動手試一試 »
佔位符可以包含 Python 程式碼,例如數學運算。
示例
在佔位符中執行數學運算,並返回結果
txt = f"The price is {20 * 59} dollars"
print(txt)
自己動手試一試 »
在我們的 字串格式化 章節中瞭解更多關於字串格式化的資訊。
W3schools 學習路徑
跟蹤您的進度 - 免費!