有,哦,有這麼多的方式來做到這一點。絕對最簡單的一個,我能想到的是:
TEMPLATE = "My name is {name}\nI am {age} years old."
for name, age in [("Tom", 20), ("Tim", 30), ("Tina", 40)]:
print TEMPLATE.format(name=name, age=age)
輸出:
My name is Tom
I am 20 years old.
My name is Tim
I am 30 years old.
My name is Tinakughjkjgjkhg
I am 40 years old.
該解決方案必將爲您得到更詳細的模板儘快變得複雜和醜陋。第一個「移動」,可到Python template strings(例如,從文檔):
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
但真正的解決方案,就我而言,是使用模板引擎:Jinja2會做的伎倆。
>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')
u'Hello John Doe!'
因此,如何在程序應該處理從第一個文件的輸入?只需用新名稱和新時代的第一個號碼替換硬編碼的字符串「Ben」?說明不是很清楚,恕我直言。 – 2012-03-02 21:40:40