# [Tutor] Re: thank%s

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 26 Jan 2001 17:40:38 -0800 (PST)

```On Fri, 26 Jan 2001 michaelbaker@operamail.com wrote:

> thanks once again (this is not the first time you have helped me out). I
> almost looked at the Fancier Input/Output before sending to the list,
> although now that I have I'm not so sure I wouldn't have sent to the list
> anyway. I don't qutie follow this:
>
>  >>> import string
>  >>> for x in range(1,11):
> ...     print '%2d %3d %4d' % (x, x*x, x*x*x)
> ...
> 1       1       1
> 2       4       8
> 3       9       27
> 4       16      64
> 5       25      125
> 6       36      216
> 7       49      343
> 8       64      512
> 9       81      729
> 10      100     1000
>
> %2d, %3d, %4d ???????????

Actually, you'd be surprised; it's a documented BUG that string
interpolation isn't explained!

http://sourceforge.net/bugs/?func=detailbug&bug_id=121207&group_id=5470

The Python implementers forgot to explain how it works, so don't worry if
you can't find information on this stuff.

What '%2d' means is that when we interpolate, we should make sure that it
fills up at least 2 spaces.  I think that this term is called "padding to
2 spaces", and it's useful when we want more refined control over the
format.

Let's play around with the interpreter:

###
>>> print '** %d **' % 42
** 42 **
>>> print '** %1d **' % 42
** 42 **
>>> print '** %2d **' % 42
** 42 **
>>> print '** %3d **' % 42
**  42 **
>>> print '** %4d **' % 42
**   42 **
>>> print '** %5d **' % 42
**    42 **
###

So it gives us a little more control over the format of whatever we print
out.  Often, we'll see this stuff when we need things to align just right.

Although this is pretty powerful already, we can get more fine-tuned
control when we try printing floating point numbers.  Here's an example:

###
>>> print '** %f **' % pi
** 3.141593 **
>>> print '** %3f **' % pi
** 3.141593 **
>>> print '** %3.0f **' % pi
**   3 **
>>> print '** %3.1f **' % pi
** 3.1 **
>>> print '** %3.2f **' % pi
** 3.14 **
>>> print '** %.40f **' % pi
** 3.1415926535897931159979634685441851615906 **      # wow...
###

When we say:

print '%3.2f' % pi

we're telling Python: "Make it fit at least three spaces, and leave room
for 2 decimal places."

Play around with it a bit more.  I was surprised that 'pi' was defined to
so many decimals!  *grin*

Hope this helps!

```