expletive inserted Does cursing make you feel better?

Python String Interpolation

AKA string formatting, AKA Putting values of variables into strings, AKA that thing you do with the funny symbols to get the values of variables inside strings.

At the most basic level, most programmers find that at some point they need to insert the values of a whole bunch of variables into a string. The naive approach is generally to concatenate a bunch of strings together.

>>>first_name = 'Zack'
>>>last_name = 'Halbrecht'
>>>output = "Hello " + first_name + " " + last_name
>>>print output
'Hello Zack Halbrecht'

Besides being inefficient to concatenate strings this way, what if one of the variabes you are trying to interpolate isn’t a string, but an integer? Then you’ve got to go and cast each variable using str()? Ugly. Ew. I can’t even write the code demonstrating this out of priciple. Luckily, there’s a better way. Well, there are actually two.

The first one basically dictates that you are going to create a string, and within that string you will put in placeholders where you want your variables to end up. The placeholder marker is a combination of the percent symbol (%) and a conversion type symbol which is going to determine how a variable’s value is formatted within the string. More on this later. After the string, you use the string formatting operator (% again) and pass it a tuple of the variables you want to appear in the string, in the order you want them to appear.

>>>output = "%s %s" % (first_name, last_name)
>>>print output
'Zack Halbrecht'

Damn. That’s concise. So what’s going on here? %s is a placeholder for a string. The first %s will get replaced by the first value of the tuple in this case, the value of first_name. Same with the second %s and the second value of the tuple. This is great when you’ve got less than five variables to interpolate, but what if you have 10? 20? Some huge amount? You don’t want to worry about the ordering. Well, of course there’s an easy way to deal with this situation too.

>>>output = "%(fname)s %(lname)s" % {'fname': first_name, 'lname': last_name}
>>>print output
'Zack Halbrecht'

OK. Same concept. Except this time we’re giving our % operator a dictionary of name/value pairs and our output string contains identifiers that act as lookup keys on the dictionary. Cool. We no longer have to worry about ordering. When using this method, every placeholder inside the string MUST have a parenthesized identifier. Another benefit of using this method is that if you want to insert the value of a variable in more than one place, it only has to be specified once in the dictionary. Sweet.

Oh duh, and one of the coolest things about this is that interpolation will actually do type coercion. So if you’ve got something like:

>>>output = "%(fname)s %(lname)s is %(age)i" % {'fname': first_name, 'lname': last_name, 'age': 28.5}

That %i is telling the interpolation operator to take the value of the age variable, whatever it is, in this case a float, and convert it into its string representation as an integer (using the %i). Pretty sweet. Normal concatenation with + will just get you a nice fat ValueError there.

>>>print output
'Zack Halbrecht is 28'

I realize a lot of this is covered in the truly wonderful Dive Into Python, but I was surprised to learn that the technique of using a dictionary instead of a tuple wasn’t covered. Additionally it seems that when just starting out programming in general, not a lot of people know this process as ‘string interpolation’ or ‘string formatting’, and it might help someone out there to have an article that covers it as one of the silly ways its described in the intro. Thoughts?


6 Comments

I pretty much loathe string concatenation, but I didn’t know about the dictionary method. Pretty sweet.

Posted by Afshin on 2 July 2008 @ 11am

Thanks for posting this information, it was helpful.

Posted by Jason on 31 July 2008 @ 2pm

There’s also the new str.format() method, which is standard in Python 3, as described in http://docs.python.org/library/string.html#formatstrings

Posted by Ludovico on 16 August 2009 @ 12pm

Awesome!!! Thank you soo much! Love using a hash for times when I have lots of variables to use in a string.

Posted by Mike Grace on 19 October 2010 @ 5pm

Great article. I hadn’t seen the dictionary method before.

P.S. You may be interested to know this article is the number one result for “python insert variables into string” in google. The search string is one of the strings google recommends when you start typing it.

Posted by Caligo on 20 August 2011 @ 11pm

I literally jumped out of my chair and danced after rdeinag this!

Posted by Alexavia on 22 September 2011 @ 6am

Leave a Comment