Python格式化字符串常量f-string總結
本文主要總結在Python中如何使用格式化字符串常量f-string(Formatted string literals)。在 Python 程序中,大部分時間都是使用 %s 或 format 來格式化字符串,在 Python 3.6 中新的選擇 f-string可以用於格式化字符串。相比於其他字符串格式方式,f-string更快,更易讀,更簡明且不易出錯。f-string通過f或 F 修飾字符串,如f’xxx’ 或 F’xxx’),以大括號 {}表示被替換的字段。對齊的格式在冒號後指定;例如:f’{price:.3},其中price是變量名。
文章目錄
1 語法
1.1 Python字符串格式
以下示例總結了Python中的字符串格式設置選項。
name = 'Peter'
age = 23
print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')
Peter is 23 years old
Peter is 23 years old
Peter is 23 years old
這個是最古老的方式,通過%代替變量,如下所示:
print(’%s is %d years old’ % (name, age))
從Python 3.0開始,format()引入了該功能以提供高級格式化選項。如下所示:
print(’{} is {} years old’.format(name, age))
從Python 3.6開始,Python f-string用於格式化變量,如下所示:
print(f’{name} is {age} years old’)
1.2 Python f-string中使用表達式
我們可以將表達式放在{}方括號之間,如下所示:
bags = 3
apples_in_bag = 12
# 對f-string中的表達式求值
print(f'There are total of {bags * apples_in_bag} apples')
There are total of 36 apples
1.3 Python f-string中使用字典
user = {'name': 'John Doe', 'occupation': 'gardener'}
# 獲得對應的值
print(f"{user['name']} is a {user['occupation']}")
John Doe is a gardener
1.4 Python多行f-string
def mymax(x, y):
return x if x > y else y
a = 3
b = 4
print(f'Max of {a} and {b} is {mymax(a, b)}')
Max of 3 and 4 is 4
1.5 Python f-string對象
Python f-string也接受對象;這些對象必須定義有__str__()或__repr__()函數。
class User:
def __init__(self, name, occupation):
self.name = name
self.occupation = occupation
def __repr__(self):
return f"{self.name} is a {self.occupation}"
u = User('John Doe', 'gardener')
print(f'{u}')
John Doe is a gardener
1.6 Python f-string中轉義字符
爲了轉義{},我們將嵌入{{}}轉義。單引號用反斜槓字符轉義。如下所示:
print(f'Python uses {{}} to evaludate variables in f-strings')
print(f'This was a \'great\' film')
Python uses {} to evaludate variables in f-strings
This was a 'great' film
1.7 Python f-string中格式化 datetime
示例顯示格式化的當前日期時間。日期時間格式說明符跟在:字符後面
import datetime
now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')
2020-06-17 20:39
1.8 Python f-string中格式化 floats
浮點值帶有f後綴。我們還可以指定精度:小數位數。精度通過.後的值設定。例如.2f表示浮點數值,小數點後保留兩位小時。如下所示輸出兩位和五位小數位數:
val = 12.3
print(f'{val:.2f}')
print(f'{val:.5f}')
12.30
12.30000
1.9 Python f-string中字符寬度
字符寬度說明符設置值的寬度。如果該值短於指定的寬度,則該值可以用空格或其他字符填充。如下程序所示打印三列。每個列都有一個預定義的寬度。第一列使用0填充較短的值,如果不填默認使用空格填充。
for x in range(1, 11):
print(f'{x:02} {x*x:3} {x*x*x:4}')
01 1 1
02 4 8
03 9 27
04 16 64
05 25 125
06 36 216
07 49 343
08 64 512
09 81 729
10 100 1000
1.10 Python f-string對齊字符串
默認情況下,字符串左對齊。我們可以使用>字符將字符串向右對齊。>字符跟在冒號字符後面。如下所示我們有四根不同長度的字符串。我們將輸出的寬度設置爲10個字符。這些值向右對齊。
s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'
print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')
a
ab
abc
abcd
1.11 Python f-string中進製表示
數字可以具有各種進制,例如十進制或十六進制。
# hexadecimal
print(f"{a:x}")
# octal
print(f"{a:o}")
# scientific
print(f"{a:e}")
3
3
3.000000e+00
2 參考
https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals