电竞比分网-中国电竞赛事及体育赛事平台

分享

好程序員Python學習路線分享f-string更酷的格式化字符串

 好程序員IT 2019-08-26

  好程序員Python學習路線分享f-string更酷的格式化字符串,在 Python 中,大家都習慣使用 %s 或 format 來格式化字符串,在 Python 3.6 中,有了一個新的選擇 f-string。

使用對比

我們先來看下 Python 中已經(jīng)存在的這幾種格式化字符串的使用比較。

# %s
username = 'tom'
action = 'payment'
message = 'User %s has logged in and did an action %s.' % (username, action)
print(message)
# format
username = 'tom'
action = 'payment'
message = 'User {} has logged in and did an action {}.'.format(username, action)
print(message)
# f-string
username = 'tom'
action = 'payment'
message = f'User {user} has logged in and did an action {action}.'
print(message)
f"{2 * 3}"
# 6
comedian = {'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 是當前最佳的拼接字符串的形式,擁有更強大的功能,我們再來看一下 f-string 的結構。

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)換標志 !a a = '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

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多