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

Store formatted strings, pass in values later?

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

是否可以使用 占位符 存储格式化字符串并在以后传递实际值?

我在想这样的事情:

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

print(d["message"].format("Dave"))

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

你用的是f-string;它已经在其中插入了 0 。您可能想删除 f 那里

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

print(d["message"].format("Dave"))
Hi There, Dave

问题:将 f-String 与 str.format

混合
Technique Python version
f-String since 3.6
str.format since 2.6

您的字典值包含 f-String立即计算。 因此,花括号内的表达式(原为 {0})被直接插值(变为 0),因此赋值变为 "Hi There, 0".

当应用 .format 参数 "Dave" 时,这被忽略了,因为字符串已经丢失了模板 {} 内部。最后字符串按原样打印:

Hi There, 0

尝试使用 f-String

如果我们使用像 name 这样的变量名而不是常量整数 0 会怎样?

让我们试试 Python 的控制台 (REPL):

>>> d = {"message": f"Hi There, {name}"}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined

OK,我们必须先定义变量。假设我们做到了:

>>> name = "Dave"; d = {"message": f"Hi There, {name}"}
>>> print(d["message"])
Hi There, Dave

这行得通。但它要求花括号内的变量或表达式在运行时有效,在定义位置:name 需要在之前定义。

str.format

折断长枪

有原因

  • 当您需要从外部资源(例如文件或数据库)读取模板
  • 当不是变量而是占位符配置时独立于您的源

那么索引占位符应该优先于命名变量。

考虑具有值 "Hello, {1}. You are {0}." 的给定数据库列 message。它可以独立于实现(编程语言、周围代码)阅读和使用。

例如

  • 在Java中:MessageFormat.format(message, 74, "Eric")
  • 在 Python 中:message.format(74, 'Eric')

另请参阅: Format a message using MessageFormat.format() in Java