使用Python的string.Template類 - 如何在包含空格的字典中使用$ {}作爲字段?Python string.Template:替換包含空格的字段
E.g.
t = string.Template("hello ${some field}")
d = { "some field": "world" }
print(t.substitute(d)) # Returns "invalid placeholder in string"
編輯:這是最接近我能得到,需要提醒的是,所有的變量都需要包裝在一個括號(否則所有空格分隔的單詞會被匹配)。
class MyTemplate(string.Template):
delimiter = '$'
idpattern = '[_a-z][\s_a-z0-9]*'
t = MyTemplate("${foo foo} world ${bar}")
s = t.substitute({ "foo foo": "hello", "bar": "goodbye" })
# hello world goodbye
啊,這看起來不錯 - 它是唯一的Python 3?我可能應該提到Python 2.7x支持的必要性 – funseiki
您可以簡單地使用'str'的'.format'方法:'print('hello {some field}'。format(** d))' –