【发布时间】:2020-08-28 07:23:44
【问题描述】:
我已经阅读了 How do I convert a string into an f-string? 和 How to postpone/defer the evaluation of f-strings? 并看到了许多使用 exec 来推迟执行 f 字符串的(有效)解决方案,例如:
template = "My name is {name} and I am {age} years old"
name = 'Abcde'
age = 123
s = eval('f"""' + template + '"""') # My name is Abcde and I am 123 years old
是否有一个内部 Python 函数(在众多双下划线 __something__ 函数中)定义解释器如何“运行”/“插入”一个 f 字符串?
Python源码中是否有__runfstring__之类的东西,负责代码的执行?如果是这样,我们可以自己调用这个函数吗:
s = __runfstring__(template)
在最新的 Python 版本中? (3.7 或 3.8+)
【问题讨论】:
-
是否有理由需要为此使用 f 字符串而不是传统的字符串格式,例如直接打电话给
template.format(name=name, age=age)? -
@TomDalton:是的,如果有很多变量,为了避免必须做
.format(name=name, age=age, ..., var1234=var1234)。但更一般地说,出于好奇,我想知道哪个__internalfunction__执行 f 字符串。 -
如果有帮助,您可以将字典传递/解压缩到
.format?我认为简短的回答可能是 f 字符串不适用于您的用例。 -
通过调用函数来做你想做的事情的问题是,该函数中不存在局部变量,它需要做一些“令人惊讶”的事情。在调用范围内发现变量。
-
@TomDalton 在某些场景中,您事先并不确切知道所有变量,并且您不想对其进行硬编码(例如:您使用新变量更改模板)
标签: python python-3.x string string-interpolation f-string