存储格式化字符串,稍后传入值?

Amo*_*kar 3 python templates string-formatting python-3.x f-string

我有一本有很多字符串的字典。

是否可以存储带有占位符的格式化字符串并稍后传入实际值?

我在想这样的事情:

d = {
  "message": f"Hi There, {0}"
}

print(d["message"].format("Dave"))
Run Code Online (Sandbox Code Playgroud)

上面的代码显然不起作用,但我正在寻找类似的东西。

小智 12

您使用 f 字符串;它已经插0在那里了。您可能想删除f那里

d = {
          # no f here
  "message": "Hi There, {0}"
}

print(d["message"].format("Dave"))
Run Code Online (Sandbox Code Playgroud)
Hi There, Dave
Run Code Online (Sandbox Code Playgroud)