Python template strings

String template


from string import Template
# from  w  ww . j  a  va2  s .c o m

s = Template('$x, glorious $x!')
s.substitute(x='slurm')

print s

The code above generates the following result.

Interpolating Variables Inside Strings


import string# from   www  .  java  2  s.  c om

values = [5, 3, 'blue', 'red']
s = string.Template("Variable v = $v")

for x in values:
    print s.substitute(v=x)

The code above generates the following result.

If the replacement field is part of a word, the name must be enclosed in braces.


from string import Template
# from w w w .  j a v a  2  s. com

s = Template("It's ${x}tastic!")
print s.substitute(x='slurm')

In order to insert a dollar sign, use $$.


from string import Template
# from  w w  w . j a  v  a 2s  .co  m

s = Template("Make $$ selling $x!")
print s.substitute(x='slurm')

We can supply the value-name pairs in a dictionary.


from string import Template
# w ww .jav  a2  s. c om

s = Template('A $thing must never $action.')
d = {
  'thing': 'gentleman',
  'action': 'show his socks'
}
print s.substitute(d)

HTML template


from string import Template
# from w w w.ja v a2s .  c  om
template = '''<html> 
<head><title>%(title)s</title></head> 
<body> 
<h1>%(title)s</h1> 
<paragraph>%(text)s</paragraph> 
</body>'''


data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'}
print template % data

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary