如何在预制弦乐中使用 F 弦乐?

How to use f-strings in a premade string?

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

我的示例文件:

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

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

我尝试在没有任何内容的情况下使用 .format()。但这没有用。

有没有办法用 f 弦做到这一点?或任何更清洁的方式?

"True" f-strings 只能是 python 文件中的文字字符串,所以为了语义,你所拥有的实际上是一个常规字符串,你称之为 .format在。如果你想要“真正的”f-strings 的相同功能(为 {replacement_values} 拉局部变量),你需要给 format 方法一个包含这些值的字典,可以很容易地用内置函数:locals()globals().

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

1. 老实说,保持原样,或者将参数拆分为 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,
    # ...
}