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

Python中的简单模板(请不要使用模板引擎),python,string,templates,escaping,templating,Python,String,Templates,Escaping,Templating,此代码 txt = "f'{string} a great day'" with open('new.txt', 'w', encoding='utf-8') as out: out.write(f'{string} a great day') txt = "f'{string} a great day'" with open('new.txt', 'w', encoding='utf-8') as out: out.write(txt)

此代码

txt = "f'{string} a great day'"
with open('new.txt', 'w', encoding='utf-8') as out:
    out.write(f'{string} a great day')
txt = "f'{string} a great day'"
with open('new.txt', 'w', encoding='utf-8') as out:
    out.write(txt)
在new.txt文件中写入“祝您度过愉快的一天”

此代码

txt = "f'{string} a great day'"
with open('new.txt', 'w', encoding='utf-8') as out:
    out.write(f'{string} a great day')
txt = "f'{string} a great day'"
with open('new.txt', 'w', encoding='utf-8') as out:
    out.write(txt)
没有。它写的是文字
f'{string}美好的一天'
在new.txt文件中

为什么?


有没有办法让第二段代码执行第一段代码所执行的操作?

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

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

表达式和包含表达式的字符串之间存在差异。因为汽车和汽车照片之间是有区别的。更糟糕的是:就像我有一个脑袋,我有一个脑袋在思考脑袋本身:)-看起来他们是不同的。