Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

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 115 views
1 answer 148 views
1 answer 117 views
117 views asked Mar 2, 2020 by avibootz
2 answers 122 views
...