对我来说,新的 Python 3.6 f-strings 似乎是字符串可用性的巨大飞跃,我很想在可能在旧解释器上运行的新项目中全心全意地采用它们。 2.7、3.3-3.5 支持会很好,但至少我想在 Python 3.5 代码库中使用这些。如何导入 3.6 的格式化字符串文字以供较旧的解释器使用?
我了解像 f"Foo is {age} {units} old"
这样的格式化字符串文字不会造成重大更改,因此不会包含在 from __future__ import ...
调用。但是更改没有向后移植(AFAIK)我需要确保我用 f-strings 编写的任何新代码都只能在 Python 3.6+ 上运行,这对于很多项目来说都是一个交易破坏者。
最佳答案
future-fstrings将 f 字符串引入 Python 2.7 脚本。 (我根据文档假设为 3.3-3.5。)
一旦你通过 pip install future-fstrings
安装它,你必须在你的代码顶部放置一个特殊的行。那行是:
# -*- coding: future_fstrings -*-
然后你可以在你的代码中使用格式化的字符串字面量(f-strings):
# -*- coding: future_fstrings -*-
var = 'f-string'
print(f'hello world, this is an {var}')
关于python - 我可以将 Python 3.6 的格式化字符串文字(f-strings)导入旧的 3.x、2.x Python 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42097052/