Skip to content

Format Operator in Python

Sometimes, using string substitution the code can become unreadable when you are using many substitutions, for example imagine this:

welcome = "Hi there, my name is"
name = "John"
welcome_2 = "and I am"
age = 37
welcome_3 = "years old"

print "%s %s %s %s %s" % (welcome, name, welcome_2, age, welcome_3)
Output: Hi there, my name is John and I am 37 years old 

While this looks like a bit of a mess it will work, but lets see how it can be improved:

name = "John"
age = 37
print "Hello, my name is {} and I am {} years old".format(name, age)
Output: Hello, my name is John and I am 37 years old

But is this any better? We are using the same number of substitutions? What we can do is use a number to reference the variables, so that we are no longer relying on the order:

name = "John"
age = 37
print "Hello, I am {1} years old, my name is {0}".format(name, age)
Output: Hello, I am 37 years old, my name is John

This makes the code much easier to read and maintain, but the most important part is that we can reuse the values.

We can also do this with dictionary values:

name = "John"
age = 37
print "Hello, my name is {name} and I am {age} years old".format(name=name, age=age)
Output: Hello, my name is John and I am 37 years old
Published inMayaPythonscripting