将字符串转换为 f 字符串
如何将经典字符串转换为 f 字符串?
How do I transform a classic string to an f-string?
variable = 42
user_input = "The answer is {variable}"
print(user_input)
输出:答案是{variable}
f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)
期望输出:答案是42
f 字符串是语法,而不是对象类型.您不能将任意字符串转换为该语法,该语法会创建一个字符串对象,而不是相反.
An f-string is syntax, not an object type. You can't convert an arbitrary string to that syntax, the syntax creates a string object, not the other way around.
我假设您想使用 user_input
作为模板,所以只需使用 str.format()
方法 user_input
对象:
I'm assuming you want to use user_input
as a template, so just use the str.format()
method on the user_input
object:
variable = 42
user_input = "The answer is {variable}"
formatted = user_input.format(variable=variable)
如果你想提供一个可配置的模板服务,创建一个包含所有可以插入的字段的命名空间字典,并使用 str.format()
和 **kwargs
> 调用语法来应用命名空间:
If you wanted to provide a configurable templating service, create a namespace dictionary with all fields that can be interpolated, and use str.format()
with the **kwargs
call syntax to apply the namespace:
namespace = {'foo': 42, 'bar': 'spam, spam, spam, ham and eggs'}
formatted = user_input.format(**namespace)
然后用户可以在 {...}
字段中使用命名空间中的任何键(或者没有,忽略未使用的字段).
The user can then use any of the keys in the namespace in {...}
fields (or none, unused fields are ignored).