簡體   English   中英

Python 3.6中的格式化字符串文字是什么?

[英]What are formatted string literals in Python 3.6?

Python 3.6的一個功能是格式化字符串。

這個SO問題 (python-3.6中帶有'f'前綴的字符串)詢問格式化字符串文字的內部,但我不理解格式化字符串文字的確切用例。 我應該在哪些情況下使用此功能? 是不是明確比隱含更好?

簡單比復雜更好。

所以這里我們有格式化字符串。 它為字符串格式提供了簡單性,同時保持代碼顯式(與其他字符串格式化機制的硬件)。

title = 'Mr.'
name = 'Tom'
count = 3

# This is explicit but complex
print('Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count))

# This is simple but implicit
print('Hello %s %s! You have %d messages.' % (title, name, count))

# This is both explicit and simple. PERFECT!
print(f'Hello {title} {name}! You have {count} messages.')

它旨在替換str.format以進行簡單的字符串格式化。

專業:F-literal有更好的表現。(見下文)

Con:F-literal是一個新的3.6功能。

In [1]: title = 'Mr.'
   ...: name = 'Tom'
   ...: count = 3
   ...: 
   ...: 

In [2]: %timeit 'Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count)
330 ns ± 1.08 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %timeit 'Hello %s %s! You have %d messages.'%(title, name, count)
417 ns ± 1.76 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %timeit f'Hello {title} {name}! You have {count} messages.'
13 ns ± 0.0163 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

比較所有4種字符串格式的表現

title = 'Mr.' name = 'Tom' count = 3

%timeit 'Hello {title} {name}! You have {count} messages.'.format(title=title, name=name, count=count)

每回路198 ns±7.88 ns(平均值±標准偏差,7次運行,每次1000000次循環)

%timeit 'Hello {} {}! You have {} messages.'.format(title, name, count)

每回路329 ns±7.04 ns(平均值±標准偏差,7次運行,每次1000000次循環)

%timeit 'Hello %s %s! You have %d messages.'%(title, name, count)

每個循環264 ns±6.95 ns(平均值±標准偏差,7次運行,每次1000000次循環)

%timeit f'Hello {title} {name}! You have {count} messages.'

每個環路12.1 ns±0.0936 ns(平均值±標准偏差,7次運行,每次100000000次循環)

所以最新的字符串格式化方式是python3.6也是最快的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM