[Tutor] %d

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 22 May 2001 14:26:07 -0700 (PDT)


On Tue, 22 May 2001, Patrick Kirk wrote:

> In Alan Gauld's tutorial page 2 you suddenly move from gentle hand holding
> to this:
> 
> >>>print "The sum of %d and %d is: %d" % (v,w,x)
> 
> v,w,x are variables and have integer values.  d is less clear.  And %?
>
> I thought % was for the modulus function.  So what is that % doing in
> front of d which I assume to be a built in variable?  And what is the
> % in front of the curly brackets?

In this particular case, Python borrows some of the syntax of "formatted
strings" in C.  When we're using the '%' operator with strings, we're now
doing a string formatting operation instead of the modulus.

By string formatting, this means that everywhere you see '%d' in the
string, it will get replaced by the corresponding integer value in the
tuple.  For example, in the string:

    "The sum of %d and %d is: %d"

there are three '%d' parts, and each will be replaced by the values of v,
w, and x, respectively.  Think Mad Libs, and you'll have the general idea
of how string interpolation works.


You might wonder why we have this sort of stuff: this seems equivalent to
doing:

    "The sum of " + v + " and " + w + " is: " + x

and, in this case, we'll get a similar result.  The difference, though, is
that string formatting is generally easier to write, and less messy
looking.  Also, it gives us really fine control over the way we want our
strings to look.


For example, let's say that we're doing stuff with money.

###
>>> salary = 12345.29
>>> tax = salary * .14
>>> tax
1728.3406000000002
###

If we want to just print out tax as "1728.34", we can use a neat feature
of formatting:

###
>>> "%.2f" % tax
'1728.34'
###

which means, "We'll replace (interpolate) a floating point number where
'%.2f' appears, and this number will only have, at most, 2 decimal
places."  I'm using a "%f" thing, which formats a floating point value
into the string.


(Sometimes, string formatting is referred to as "interpolation", which is
sometimes why I'll slip and say "interpolation."  Habits are hard to
break.)

You can find out more about string formatting here:

    http://www.python.org/doc/current/lib/typesseq-strings.html

Hope this helps!