在python中动态解析变量

VK.*_*VK. 1 python dynamic-variables f-string

说我有一个字符串 -

my_str = "From {country} with Love"

变量country目前不可用,稍后将设置为

country = "Russia".

现在我可以用动态解析的内联变量值打印字符串吗?就像是 -

print(f"{my_str}")

这将输出

From Russia with Love

我尝试使用 eval() 但没有帮助。

And*_*eas 5

my_str = "From {} with Love"
country = "Russia"
print(my_str.format(country))
Run Code Online (Sandbox Code Playgroud)

如果您喜欢使用名称,您还可以执行以下操作:

my_str = "From {country} with Love"
country = "Russia"
print(my_str.format(country=country))
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案。 (2认同)