好程序員Python學(xué)習(xí)路線分享f-string更酷的格式化字符串,在 Python 中,大家都習(xí)慣使用 %s 或 format 來格式化字符串,在 Python 3.6 中,有了一個新的選擇 f-string。
使用對比
我們先來看下 Python 中已經(jīng)存在的這幾種格式化字符串的使用比較。
# %susername = 'tom'action = 'payment'message = 'User %s has logged in and did an action %s.' % (username, action)print(message)# formatusername = 'tom'action = 'payment'message = 'User {} has logged in and did an action {}.'.format(username, action)print(message)# f-stringusername = 'tom'action = 'payment'message = f'User {user} has logged in and did an action {action}.'print(message)f"{2 * 3}"# 6comedian = {'name': 'Tom', 'age': 20}f"The comedian is {comedian['name']}, aged {comedian['age']}."# 'The comedian is Tom, aged 20.'
相比于常見的字符串格式符 %s 或 format 方法,f-strings 直接在占位符中插入變量顯得更加方便,也更好理解。
方便的轉(zhuǎn)換器
f-string 是當(dāng)前最佳的拼接字符串的形式,擁有更強大的功能,我們再來看一下 f-string 的結(jié)構(gòu)。
f ' <text> { <expression> <optional !s, !r, or !a> <optional : format specifier> } <text> ... '
其中 '!s' 調(diào)用表達式上的 str(),'!r' 調(diào)用表達式上的 repr(),'!a' 調(diào)用表達式上的 ascii().
默認情況下,f-string 將使用 str(),但如果包含轉(zhuǎn)換標志 !r,則可以使用 repr()
class Person:
def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'str - name: {self.name}, age: {self.age}' def __repr__(self): return f'repr - name: {self.name}, age: {self.age}'p = Person('tom', 20)
f'{p}'
# str - name: tom, age: 20
f'{p!r}'
# repr - name: tom, age: 20
- 轉(zhuǎn)換標志 !aa = 'a string'
f'{a!a}'
# "'a string'"
等價于
f'{repr(a)}'
# "'a string'"
性能f-string 除了提供強大的格式化功能之外,還是這三種格式化方式中性能最高的實現(xiàn)。
import timeittimeit.timeit("""name = "Eric"... age = 74... '%s is %s.' % (name, age)""", number = 10000)0.003324444866599663timeit.timeit("""name = "Eric"... age = 74... '{} is {}.'.format(name, age)""", number = 10000)0.004242089427570761timeit.timeit("""name = "Eric"... age = 74... f'{name} is {age}.'""", number = 10000)0.0024820892040722242