如何将经典弦乐转换为 F 弦乐?
variable = 42
user_input = "The answer is {variable}"
print(user_input)
输出: The answer is {variable}
f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)
期望的输出: The answer is 42
原文由 François M. 发布,翻译遵循 CC BY-SA 4.0 许可协议
f 字符串是 syntax ,而不是对象类型。您不能将任意字符串转换为该语法,该语法会创建一个字符串对象,而不是相反。
我假设你想使用
user_input
作为模板,所以只需在user_input
对象上使用str.format()
方法:如果你想提供一个可配置的模板服务,创建一个包含所有可以插入的字段的命名空间字典,并使用
str.format()
和**kwargs
调用语法来应用命名空间:然后,用户可以在
{...}
字段中使用命名空间中的任何键(或不使用,未使用的字段将被忽略)。