Python3.6的一个特性是格式化字符串。
This SO question(python-3.6中前缀为'f‘的字符串)询问格式化字符串文字的内部结构,但我不明白格式化字符串文本的确切用例。在什么情况下我应该使用这个特性?明示不比内隐好吗?
发布于 2016-08-22 14:26:49
简单胜于复杂。
所以这里我们已经格式化了字符串。它使字符串格式化变得简单,同时保持代码的显式(与其他字符串格式机制相比较)。
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用于简单的字符串格式设置。
发布于 2018-07-02 08:48:43
Pro: F-文字有更好的性能。(见下文)
Con: F-文字是一个新的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)发布于 2018-07-19 16:49:41
比较所有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.88ns(平均±std )。dev.7次运行中,每一次循环1000000次)
%timeit 'Hello {} {}! You have {} messages.'.format(title, name, count)
每环329 ns±7.04 ns (平均±std )。dev.7次运行中,每一次循环1000000次)
%timeit 'Hello %s %s! You have %d messages.'%(title, name, count)
每环264 ns±6.95ns(平均±std )。dev.7次运行中,每一次循环1000000次)
%timeit f'Hello {title} {name}! You have {count} messages.'
每环12.1ns±0.0936 ns (平均±std )。dev.7次运行中,每一次循环100000000次)
因此,字符串格式化的最新方法来自python3.6,也是最快的。
https://stackoverflow.com/questions/39081766
复制相似问题