Python 3.6中的f字符串 [英] f-strings in Python 3.6

查看:124
本文介绍了Python 3.6中的f字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很想研究代码风格,很有趣的是,从现在开始在所有情况下使用新风格是否会更好.

I really like to delve into code style and it's interesting to know whether from now on in all cases it would be better to use the new style.

我在Python 3.5项目中经常使用.format(),由于这种新型的字符串文字,恐怕在下一个Python版本中将不推荐使用它.

I'm using a lot the .format() in my Python 3.5 projects, and I'm afraid that it will be deprecated during the next Python versions because of this new kind of string literals.

>>> name = "Test"
>>> f"My app name is {name}."
'My app name is Test.'

格式化字符串功能是否可以完全替代旧的format()?

Does the formatted string feature come to fully replace the old format() ?

我了解它基于以下想法:

I understand that it based on the idea that:

简单胜于复杂.

Simple is better than complex.

但是,关于性能问题,它们之间有什么区别吗?还是只是具有相同功能的简单外观?

However, what about performance issues, does any difference exist between them? Or is it just a simple look of the same feature?

推荐答案

恐怕它将在下一个Python版本中弃用

不是,str.format不会出现(也没有理由)要马上离开,引入了f前缀字符串的PEP甚至

Don't be, str.format does not appear (nor has a reason) to be leaving any time soon, the PEP that introduced fprefixed-strings even states in its Abstract:

此PEP不建议删除或弃用任何现有的字符串格式设置机制.

This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.

引入了格式化字符串,以解决其他格式化字符串方法所存在的缺点;不要丢掉旧的方法,强迫上帝知道如果希望项目的代码适用于Python 3.6+,那么有多少项目可以使用f-string.

Formatted strings were introduced to address some of the shortcomings other methods for formatting strings had; not to throw the old methods away and force god-knows how many projects to use f-string's if they want their code to work for Python 3.6+.

对于这些音乐的表现,我最初的怀疑是它们可能会变慢,这是错误的,f弦乐似乎轻易地胜过了它们的.format乐曲:

As for the performance of these, it seems my initial suspicion that they might be slower is wrong, f-strings seem to easily outperform their .format counterparts:

➜ cpython git:(master) ./python -m timeit -s "a = 'test'" "f'formatting a string {a}'"
500000 loops, best of 5: 628 nsec per loop
➜ cpython git:(master) ./python -m timeit "'formatting a string {a}'.format(a='test')"
100000 loops, best of 5: 2.03 usec per loop

在撰写本文时,这些操作是针对CPython存储库的master分支完成的;它们肯定会发生变化:

These were done against the master branch of the CPython repository as of this writing; they are definitely subject to change:

  • f-strings, as a new feature, might have possible optimizations
  • Optimizations to CPython might make .format faster (e.g Speedup method calls 1.2x)

但是,实际上,不必太担心速度,不必担心您和其他人更容易理解.

But really, don't worry about speed so much, worry about what is more readable to you and to others.

在许多情况下,这将是f-strings,但是

In many cases, that's going to be f-strings, but there's some cases where format is better.

这篇关于Python 3.6中的f字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆