Skip to content

String Substitution in Python

String substitution is an efficient way to substitute variables into a string, lets take the example below:

name = "John"
age = 37

print "Hello, my name is "+name+" and I am " +str(age)+ " years old"

What we are doing is fairly obvious at this point, we have 2 variables that we want to output into a string that we have defined, and we are converting the integer (37) into a string.

But there is a better way, lets see it!:

name = "John"
age = 37
print "Hello, my name is %s and I am %s years old" % (name, age)

We are adding a %s into the string for each variable we want to insert, followed by a % and then the 2 variables (in order). Using this method the integer is automatically converted into a string.

We can also do this with a dictionary entry:

name = "John"
age = 37
print "Hello, my name is %(name)s and I am %(age)s years old" % {"name":name, "age":age}
Published inPythonscripting