String Formatting Operator

From XPUB & Lens-Based wiki
Revision as of 22:16, 6 February 2009 by Michael Murtaugh (talk | contribs) (New page: Python's % operator, or "string formatting operator" is a handy way to produce text output according to a simple template. Once you get used to the syntax, the resulting code is a bit more...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Python's % operator, or "string formatting operator" is a handy way to produce text output according to a simple template. Once you get used to the syntax, the resulting code is a bit more readable and changable than using lots of '+' and str()'s to cobble together things into a string. Read the documentation for all the details. Note that in #Python 3.0 this operator is no longer used.

In general, using the string formatting operator has the following form:

TEMPLATE % DATA => NEW STRING WITH DATA PASTED INTO TEMPLATE

Where TEMPLATE is a string, and DATA is either a single variable, a tuple of variables, or a dictionary. Note that the TEMPLATE string includes markers which use the '%' character to indicate to Python where data should get pasted in. Don't confuse the two different uses of '%'. The "outside" one, between the template and the data, is the actual operator, and is what makes the substitution actually take place.

Basic use: With a Tuple

name = "Fred"
feeling = "fantastic"
print "Hello %s, I am so happy to see you. I feel %s!" % (name, feeling)

prints:

Hello Fred, I am so happy to see you. I feel fantastic!

Note how the order of the '%' markers needs to match the order of the variables given in the data tuple.

In this case, the template has two occurences of "%s" (which means "paste here a string"). In the next example, "%d" is used to paste in a decimal (whole) number, and %f is used to paste a fracional number (note how "C-style" formatting operators are supported). In this way, it's not necessary to use the str() function.

name = "Fred"
age = 6
height = 0.666666666
"Hi my name is %s, and I am %d years old, and am %0.02f meters high." % (name, age, height)

will print:

Hi my name is Fred, and I am 6 years old, and am 0.67 meters high.

Use with a Dictionary

It's also possible to use a dictionary on the right-hand side of the % operator. In this case the template should use the format '%(NAME)s', or "%(AGE)d". Whatever name is given in the parenthese, is looked up as a key in the given dictionary. This is useful for large templates and where one variable is maybe used multiple times (and keeping track of the order of a tuple would become difficult.

Example:

VARS = {}
VARS['STYLESHEET_URL'] = "http://foo.com/styles.css"
VARS['SITE_URL'] = "http://foo.com/mysite"
VARS['TITLE'] = "My Great Page"

print """
<html>
<head>
<title>%(TITLE)s</title>
<link rel="stylesheet" type="text/css" href="%(STYLESHEET_URL)s" /> 
<script language="JavaScript" type="text/javascript" src="%(SITE_URL)s/prototype.js">
<script language="JavaScript" type="text/javascript" src="%(SITE_URL)s/scripts.js">
</script>
</head>
""" % VARS

Including a literal % in your template

When you want to include an actual percent sign (%) in your template -- you used a double percent sign! So:

percent = 26
print "you got %d%% right" % percent

prints

you got 26% right

Python 3.0

In Python version 3.0 (as of Feb 2009, not yet very widely used), string formatting is done in a new way. Namely, a "format" method is added to String objects a similar, but different, syntax.

For example:

"My name is {0}".format('Fred')