What are formatted string literals in Python 3.6?

╄→гoц情女王★ 提交于 2019-12-06 17:12:40

问题


One of the features of Python 3.6 are formatted strings.

This SO question(String with 'f' prefix in python-3.6) is asking about the internals of formatted string literals, but I don't understand the exact use case of formatted string literals. In which situations should I use this feature? Isn't explicit better than implicit?


回答1:


Simple is better than complex.

So here we have formatted string. It gives the simplicity to the string formatting, while keeping the code explicit (comprared to other string formatting mechanisms).

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.')

It is designed to replace str.format for simple string formatting.




回答2:


Pro: F-literal has better performance.(See below)

Con: F-literal is a new 3.6 feature.

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)



回答3:


Comparing Performance for all 4 ways of string formatting

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 per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

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

329 ns ± 7.04 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

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

264 ns ± 6.95 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

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

12.1 ns ± 0.0936 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

So the latest way of string formatting is from python3.6 is fastest also.



来源:https://stackoverflow.com/questions/39081766/what-are-formatted-string-literals-in-python-3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!