[英]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.