如何在Python中使用f-string输出变量及替换HTML模板变量
Python相关问题解答
问题一:如何在Python中将字符串变量以f-string格式进行打印输出?
f-string是Python 3.6+引入的超好用字符串格式化方式,操作起来特别直观。你只需要在字符串前面加上f前缀,然后把要插入的变量放在{}里就行,给你举个实际例子:
# 先定义字符串变量 username = "JohnDoe" # 用f-string打印输出 print(f"当前登录的用户是:{username}")
运行这段代码后,输出结果就是:当前登录的用户是:JohnDoe
要是需要对变量做格式调整,比如保留小数、指定显示长度,也能直接在{}里加格式说明,比如:
score = 92.5 print(f"你的考试分数是:{score:.1f}") # 输出结果:你的考试分数是:92.5
问题二:将Python变量写入HTML文档实现变量替换
你现在的问题很明确:代码只是读取了HTML文件的内容并打印,既没对模板里的{user}做变量替换,也没把替换后的内容写回文件。这里给你两种靠谱的解决方法:
方法一:使用str.format()方法(推荐,适配模板文件场景)
修改你的my_python.py代码如下:
user = "myname" # 第一步:读取HTML模板文件的内容 template_path = "../../html/forms/output.html" with open(template_path, 'r') as template_file: template_content = template_file.read() # 第二步:替换模板中的变量 rendered_html = template_content.format(user=user) # 第三步:将替换后的内容写回HTML文件(不想覆盖原模板的话,可以换个文件名写入) with open(template_path, 'w') as output_file: output_file.write(rendered_html)
方法二:使用f-string(适合简单模板字符串场景)
如果你的HTML内容比较简单,也可以直接用f-string拼接,但要把模板内容作为字符串处理:
user = "myname" # 定义HTML模板字符串 html_template = "<h1>{user}</h1>" # 用f-string替换变量 rendered_html = f"{html_template}".format(user=user) # 写入文件 with open("../../html/forms/output.html", 'w') as output_file: output_file.write(rendered_html)
执行修改后的代码后,再打开output.html,就能看到<h1>myname</h1>的期望结果了。
内容的提问来源于stack exchange,提问作者Kapil
相关产品推荐
相关产品推荐

