Matt Learns Python: Part 3 – String Formatters… or how I learned to stop worrying and love the modulo

The goal of this blog is to document my journey learning new things in the world of web development and programming. At the same time, I hope to help others learn as well. Feel free to say hello on Twitter!

Previous Post: Matt Learns Python: Part 2 – More Strings, Variables, and Math!

Hello everyone and welcome back to my series on learning things, specifically Python. Let’s jump right in. Open up your command line and start python. Type in the following:

>>> name = "Matt"
>>> print 'My name is %s' %name
My name is Matt

See that little %s? That’s called a formatter, or an interpolation operator. The % is called a modulo (which would make for a great band name). I like to think of it as a placeholder, where the formatter is replaced with the variable specified at the end.

Let’s try this:

>>> name = "Matt"
>>> age = 87
>>> print 'My name is %s and I am %d.' % (name, age)
My name is Matt and I am 87.

We’ve added another formatter (%d) and variable (age). Now do this:

>>> print 'My name is %s and I am  %d.' % (age, name)

Whoops:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

So what happened? Well, there are a number of different conversion types. The two we’ve used in this example are for strings (%s) and signed integer decimals, also known as numbers (%d). The formatters and variables must be used in the same order. When we switched age and name, our formatter was now looking at name for a number. name is a string, not a number so we were served with a TypeError.

This has been just a quick introduction, we’ll delve a bit deeper in the next post.

Further Reading: