【问题标题】:How to use f-strings in a premade string?如何在预制字符串中使用 f 字符串?
【发布时间】:2021-05-15 15:46:16
【问题描述】:

我有一个大/小问题。我将文件中的全部内容加载到字符串中。然后我想添加字符串。

我的示例文件:

Titel
Name: {name_string}
Firstname: {firstname_string}
...

一种方法是.format(name_string=name_string, firstname_string=firstname_string) 但是,当我有一个大文本文件并且它破坏了整个代码(.format() 行将是 50 行)时,这需要很长时间。

我尝试使用.format(),其中没有任何内容。但这不起作用。

有没有办法用 f-strings 做到这一点?还是更清洁的方式?

【问题讨论】:

  • 不,您只能在实际 Python 代码中使用 f 字符串。也许你应该寻找一个模板引擎
  • 如果要自动插入所有变量,可以使用.format(**locals())。如果不是,请进一步说明问题。
  • 如果您要使用的所有变量都已经在全局或本地范围内,您可以将globals()locals()的字典解包到格式的参数中:template.format(**globals())
  • 这似乎不是格式化字符串的问题,而是拥有 50 个独立但相关的变量的问题。您可能会考虑重构以使用字典来存储此数据。
  • @Manuservus 那么您在模板中引用的名称之一在本地范围内丢失,您需要定义它。这就是为什么我建议不要只使用本地变量,而是使用自己构建的字典,然后解压缩到格式函数中:template.format(**mydict)

标签: python python-3.x string text-files


【解决方案1】:

"True" f-strings 只能是 python 文件中的文字字符串,所以为了语义起见,你所拥有的实际上是一个常规字符串,你正在调用 .format on。如果您想要“真实” f 字符串的相同功能(为{replacement_values} 提取局部变量),您需要为format 方法提供这些值的字典,可以使用内置函数轻松获得:@ 987654325@和globals()

这提出了编程的一个古老问题:Are global variables bad? 简而言之......它们有其用途,但如果你将它们用作拐杖,有时它会坏掉。您在 cmets 中提到的问题就是这样一个例子。您可能在整个代码中散布了此模板的变量定义,其中一个名称略有不同,或者您错过了应该填写的一个。这就是为什么我实际上建议您不要 使用globalslocals 来创建您自己的输入字典。这基本上是您在问题中已有的内容,但是有几种方法可以清理文本以使其在 .py 文件中看起来不那么糟糕:

1. 老实说,保持原样,或者将 args 拆分为多行 format。很长的函数 args 部分没有任何问题,并且非常清楚其意图是什么。

with open('my_template.txt') as f:
    filled_template = f.read().format(
        name_string=name_string, 
        firstname_string=firstname_string,
        # ...
    )

2. 创建您自己的输入值字典,然后您可以将其传递并解压缩到format。如果您在填充模板的行旁边还有其他重要的事情要做,并且您不希望它们在视觉上丢失,这将很有帮助。

f_args = {}

f_args["name_string"] = input("enter a name")
f_args["firstname_string"] = f_args["name_string"].split()[0] #extract the first name from a full name

with open('my_template.txt') as f:
    filled_template = f.read().format(**f_args) #unpack the args dict into the `format` call

#### or if you already have the values, and just want to collect them...

f_args = {
    "name_string":name_string, 
    "firstname_string":firstname_string,
    # ...
}

【讨论】:

  • 我不想给人一种必然的印象,即全局变量是完全邪恶的,你永远不应该使用它们,但这并没有让我觉得它们是必要的。如果它们从来没有用过,语言就不会拥有它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
  • 2022-12-11
  • 2018-09-27
  • 2017-11-29
  • 2021-11-15
  • 2020-05-02
  • 2020-02-28
相关资源
最近更新 更多