Python 中的简单模板请不要使用模板引擎

问题描述

代码

txt = "f'{string} a great day'"
with open('new.txt','w',encoding='utf-8') as out:
    out.write(f'{string} a great day')

在 new.txt 文件中写入“祝您有美好的一天”。

代码

txt = "f'{string} a great day'"
with open('new.txt',encoding='utf-8') as out:
    out.write(txt)

没有。它写字面 f'{string} a great day' 在 new.txt 文件中。

为什么?

有没有办法让第二块代码做第一块代码做的事情?

解决方法

第二个代码是一个包含 f'' 的字符串,python 不会响应/格式化值。但是有一个你想要的解决方案,你必须使用 eval 函数。

txt = "f'{string} a great day'"
with open('new.txt','w',encoding='utf-8') as out:
    out.write(eval(txt))