where to buy misoprostol online how to buy valtrex
Near-Implicit String Interpolation in Python | Evan Fosmark

Near-Implicit String Interpolation in Python

A great thing about working in Python is that it provides you with numerous methods of string formatting and interpolation. Unfortunately, it isn’t as implicit as it is in PHP, where just using double-quotes will parse the string. In Python at the very minimum string interpolation requires the use of the modulo operator (%) or a custom-built function. In this article, we’ll discuss building a string interpolation function using the string.Template object and Python 3.0′s format method.

Using string.Template

This is by far my favorite way of string interpolation. It allows you to use the built in template system that comes in the string module, thus making the code short and sweet.

import sys
from string import Template
 
def interpolate(s):
	template = Template(s)
	frame = sys._getframe(1)
	return template.substitute(**frame.f_locals)
 
# Here is an example of use:
name = "mary"
animal = "lamb"
print interpolate("${name} had a little ${animal}") # prints "mary had a little lamb"

This function starts off by building a template object based on the string provided to the function. Then it grabs the last frame on the call stack so we can get access to the variables being used one step back when we called the function. Lastly, it performs the substitute method on the template object and returns the interpolated string. By using substitute, it’ll throw a KeyError if a variable is found in the string that doesn’t exist. if this is undesired, you can change it to use safe_substitute instead, which suppresses the KeyError.

Python 3.0 and string.format

In Python 3.0, a new method for string interpolation was introduced onto strings directly. It’s called format. It was brought about through PEP-3101. I’d say that in most cases, a function for implicit interpolation wouldn’t be necessary with the format method. The format method works as follows:

print "Mary had a little {animal}".format(animal="dog") # prints: "Mary had a little dog"

It uses braces with the name of the parameter inside. To set the parameter in the string, pass in a named parameter into the format method . Now, if you want a solution that functions similar to the interpolate function we built above, then here it is:

# Python 3.0 required
import sys
def interpolate(s):
	frame = sys._getframe(1)
	return(s.format(**frame.f_locals))
 
# Example of use:
name = "mary"
animal = "lamb"
print interpolate("{name} had a little {animal}")   # prints "mary had a little lamb"

This code works incredibly similar to the way using string.Template, as you can see. From an outsider’s perspective, the only difference in the interpolate function is a difference in the template format. For instance, the string.Template way of interpolating uses ${animal} or $animal, while the format method uses {animal}.

Final Thoughts

Implicit string interpolation like this can be a very useful tool, but it doesn’t need to be overused. In most situations, using the format method (if you’re using Python 3.0), and the built-in modulo operator will suffice for most string manipulation and formatting needs. Happy interpolating!

 

 

3 Comments

  1. psi wrote,

    Err. Why not just:

    foo, bar = ("Alice", "Bob")
    print "Hi ${foo} and ${bar}" % locals()
  2. Evan wrote,

    Well, for starters, that won’t work. When you use the modulo operator, you’re required to specify what type it is (in this case, a string) and it uses parenthesis rather than brackets. Your example should’ve looked more like the following:

    print "Hi %(foo)s and %(bar)s" % locals()

    While that’s all fine and dandy, it still isn’t as clear or as simple as:

    print interpolate("Hi $foo and $bar")

    Especially if you come from a PHP background. (Note: this above example only works with the first interpolate function in the article)

  3. Mark wrote,

    I don’t know any other “scripting” language that doesn’t have powerful string interpolation capabilities as part of the language. This includes all Unix shells, DOS, Perl, VAX DCL, and even IBM JCL. Python doesn’t have some very practical fundamental capabilities.

Leave a comment