How to use string.Template (Template String) in Python

3 Answers

0 votes
import string   

data = {'var': 'python'}     

t = string.Template("Variable: $var - ${var}")
print('Template: ', t.substitute(data))   



'''
run

Template:  Variable: python - python   

'''

 



answered Apr 26, 2019 by avibootz
0 votes
from string import Template

s = "Tom"

t = Template('Hi $name')

print(t.substitute(name = s))



'''
run

Hi Tom

'''

 



answered Apr 26, 2019 by avibootz
0 votes
import string     

data = {'s': 'python'}     
t = string.Template("$x")     
try:         
    print('substitute: ', t.substitute(data))     
except KeyError as err:
    print('ERROR:', str(err))     

print('safe_substitute:', t.safe_substitute(data))



'''
run

ERROR: 'x'
safe_substitute: $x

'''

 



answered Apr 26, 2019 by avibootz

Related questions

1 answer 232 views
1 answer 249 views
1 answer 225 views
225 views asked Mar 2, 2020 by avibootz
2 answers 254 views
...