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

问题描述

我想将我的用户变量从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)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...