是否可以动态设置模板字符串?

问题描述 投票:0回答:2

我想在程序外部配置一个模板字符串,然后在运行时应用它:

my_string = "hello {country}" # ← this string would be read in from an external configuration file
country = "France"
print(f%%my_string%%) # ← the place where the magic happens

这可能吗?或者是否有正确的方法来做到这一点?

python string templates
2个回答
-1
投票

你可以这样做:

my_string.format(country=country)

看看

str.format()
方法就可以了。


-1
投票

是的,创建一个文件,例如

example.txt
。使用
open()
方法打开文件,然后使用
readline()
将第一行读入字符串。

然后写一些类似的内容:

with open('example.txt') as f1:
country = "France"
print(f1.readline().replace('{country}', country))
© www.soinside.com 2019 - 2024. All rights reserved.