[英]Simple template in Python (no templating engines please)
這段代碼
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', 'w', encoding='utf-8') as out:
out.write(txt)
沒有。 它在 new.txt 文件中寫入文字f'{string} a great day'
。
為什么?
有沒有辦法讓第二塊代碼做第一塊代碼的作用?
第二個代碼是一個包含f''
的字符串,並且 python 不會反應/格式化值。 但是有你想要的解決方案,你必須使用eval function。
txt = "f'{string} a great day'"
with open('new.txt', 'w', encoding='utf-8') as out:
out.write(eval(txt))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.