【问题标题】:Store formatted strings, pass in values later?存储格式化字符串,稍后传入值?
【发布时间】:2021-12-29 18:41:41
【问题描述】:

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

是否可以使用 占位符 存储格式化字符串,然后再传入实际值?

我在想这样的事情:

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

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

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

【问题讨论】:

  • 你可以创建一个 lambda 函数供以后调用
  • 你是什么意思它不起作用,它打印对我来说是正确的。我看到你现在为f-strings 编辑了它,但你之前的尝试工作正常
  • 呃,当“消息”不是 f 字符串时,您的代码运行良好。这仍然是 Python3 中有效的格式化方法

标签: python python-3.x templates string-formatting f-string


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    问题:将 f-String 与 str.format 混合

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

    您的 dict-value 包含一个 f-String,它会立即评估。 所以花括号内的表达式(原为{0})直接插值(变为0),因此赋值为"Hi There, 0"

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

    你好,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
    

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

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

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

    str.format破矛

    有原因

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

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

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

    例如

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2022-10-13
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 1970-01-01
      • 2014-09-24
      相关资源
      最近更新 更多