python-3.x - 使用变量定义的 f 字符串

标签 python-3.x

我经常使用 string.format()用于将键值对插入到字符串模板中。新款Pep 498 f-strings 已经被推荐了一段时间,但对于这种行为,它们似乎是一个糟糕的选择。

例如,如果我想创建一个新的 f_string,我需要先创建变量:

>>> date = 22
>>> date2 = f'this is a {date}'
>>> date2
'this is a 22'

现在,如果我尝试通过创建 f-string 来执行相同的操作模板但没有初始化替换值我得到了预期的 NameError
>>> date_template = f'this is a new {date_new}'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'date_new' is not defined

因为无法将字符串转换为 f-stringf-strings似乎主要是合成糖。是否有不明显的使用方式 f-strings作为模板还是我应该继续使用 string.format()string.format_map() ?

最佳答案

目前,似乎没有比 str.format 更好的方法了。和 str.format_map .
搜索后Index of Python Enhancement Proposals ,我找到了这两个相关的 PEP:PEP 501 (通用字符串插值)和 PEP 502 (字符串插值 - 扩展讨论)。 PEP 501 已被推迟 this note在 PEP 文件中:

This PEP is currently deferred pending further experience with PEP 498's simpler approach of only supporting eager rendering without the additional complexity of also supporting deferred rendering.


我没有找到有关 PEP 501 future 计划的任何信息。

有一种方法可以绕过 locals() 的一些限制。提到 here .
在下面的例子中,当 f1被称为它抛出一个 KeyError因为 locals()返回 dict具有 f2 范围内的所有变量,其中不包含 x .

def f1():
    x = 4
    def f2():
        return 'x={x}'.format_map(locals())
    return f2()
当在外部作用域中定义的变量未在函数中使用时,解释器不会浪费资源,包括在闭包中包含该变量。口译员无法分辨 x实际上用于 f2因为该用途是在字符串中指定的,其中解释器不检查变量的使用情况。因为 x似乎没有用于 f2 ,当 f1 时丢弃返回以节省内存。
我们可以通过显式使用 x 来覆盖此行为。在 f2 .
def f1():
    x = 4
    def f2():
        x
        return 'x={x}'.format_map(locals())
    return f2()
注意:如果x已在 f2 中使用没有必要再提了。例如:
def f1():
    x = 4
    def f2():
        print(x)
        return 'x={x}'.format_map(locals())
    return f2()
print 的(有点无意义的)调用这里使用 x所以没有必要在其他任何地方明确使用它。

关于python-3.x - 使用变量定义的 f 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47290348/

相关文章:

python - TypeError : __init__() got an unexpected keyword argument 'checksec'

Python,获取字典,并生成列表(单词> 1,最常见的单词,最长的单词)

python - 用逗号解析 pandas 中的 CSV 文件

python - 类型错误 - 无法将 'User' 对象隐式转换为 str

python - Emacs 中的 Python 2 和 3

python - 遍历数组

python - python3的pycharm编码错误

python - PyCrypto 在 Windows 上安装错误

python - 使用 pytest 运行单个测试方法失败(未找到)

python - .pip 配置了需要 TLS/SSL 的位置,但是 Python 中的 ssl 模块不可用。 (Windows 10)