Monday, November 2, 2009

Interpolating Variables Inside Strings










Interpolating Variables Inside Strings






s = string.Template("Variable v = $v")
for x in values:
print s.substitute(v=x)




Python provides the capability to interpolate variables inside strings. This functionality provides the ability to create string templates and then apply variable values to them based on the state of an existing variable.


Interpolating variables is accomplished in two steps. The first step is to create a string template, using the Template(string) method, which includes the formatted text and properly placed variable names preceded by the $ character.


Note



To include a $ character in your template string use a double $$ set. The $$ will be replaced with a single $ when the template is applied.




Once the template has been created, the second step is to apply a variable value to the template using the substitute(m, [, kwargs]) method of the Template class. The argument m can be a specific assignment, a dictionary of variable values, or a keyword list.


import string

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

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


var_str.py


Variable v = 5
Variable v = 3
Variable v = blue
Variable v = red


Output from var_str.py code












No comments: