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

时间:2016-08-22 14:10:50

标签: python python-3.6 f-string

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

This SO question(python-3.6中带有'f'前缀的字符串)询问格式化字符串文字的内部,但我不理解格式化字符串文字的确切用例。我应该在哪些情况下使用此功能?是否明显比隐含更好?

3 个答案:

答案 0 :(得分:25)

  

简单比复杂更好。

所以这里我们已经格式化了字符串。它使字符串格式化变得简单,同时保持代码显式(与其他字符串格式化机制相同)。

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替换为简单的字符串格式。

答案 1 :(得分:3)

专业版:F-literal性能更好。(见下文)

缺点: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)

答案 2 :(得分:1)

比较四种字符串格式设置的性能

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次,每个循环1亿次)

因此,最新的字符串格式化方法来自python3.6也是最快的。