如何在 python 中将字符串变量打印为 f 字符串

How to print string variable as f string in python

我想将我的用户变量从我的 python 脚本打印到 html 文档,这就是我必须这样做的方式。 我该怎么做?

my_python.py

user = "myname"
with open("../../html/forms/output.html") as output:
    print(output.readlines())

output.html

<h1>{user}</h1>

预期输出:
<h1>myname</h1>

实际输出:
<h1>{user}</h1>

f-string 是一种语法而不是对象,因此 - 您无法将字符串转换为 f-string.

如果您知道模板文件中“变量”的名称,您可以:

output.read().format(user=user)