I am using string template to replace placeholders. My current scenario is to have variable for the key instead of the string to be replaced.
Below is an example of what i am trying to achieve.
import traceback
from string import Template
def test_substitute():
try:
tpl = Template("My $testname is ...")
name = 'testname'
tpl_str = tpl.substitute(name='test')
print(tpl_str)
except:
traceback.print_exc()
if __name__=="__main__":
test_substitute()
In the above example, name is a variable that holds any string like 'testname' or 'testname1' but i the key cannot be a variable as it consider a whole string.
Is there a way to make that key as a variable?
If not i would rather go with string replace.
-Bala
How about this
import traceback
from string import Template
def test_substitute():
try:
tpl = Template("My $testname is ...")
name = 'testname'
tpl_str = tpl.substitute(**{name: 'test'})
print(tpl_str)
except:
traceback.print_exc()
if __name__=="__main__":
test_substitute()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.