[Tutor] Asterisk

Jeff Grimmett grimmtooth@softhome.net
Wed Dec 4 20:23:02 2002


> >> At 06:48 PM 12/4/2002 -0330, Adam Vardy wrote:
> >>  > Why does this happen? It is a strange expression.
> >>  > >>> '%*.*f' % (6,3,1.41421356)
> >>  > ' 1.414'
>
> >> That's what I'd expect. Did you rtfm?
>
> Well the answer is direct from the Python shell prompt. So anything it
> says should be expected.

> I don't follow this. I understand you're a manual kind of parsing guy.
> But I just started learning Python this week. Anyone else want to explain
> how it reaches the result?

Hm, well, this IS a tutor list so I'll try some tutoring :-D

I think that what the problem is that you're trying to evaluate this as an
equation, which it ain't really. My appologies in advance if I am mistaken.

The expression

  '%*.*f' % (6,3,1.41421356)

is actually a print FORMATTING statement and not an equation at all. It
breaks down into two sections. The first, the portion to the LEFT of the
second % sign, is what you want to print, including formatting placeholders.
Formatting placeholders begin with a % as well, and allows you to include
just about anything.  Common % formats are %d (placeholder for a number), %f
(placeholder for a floating point number), %s (placeholder for a string). If
you are at all familiar with C printf() formatting, these are really simple
to get your head around.

This formatting statement includes the moderately advanced '*' token. This
indicates that a number, provided in the 'arguments' will be substituted for
this asterisk. If there are more than one asterisks in a formatting
statement, the first number will be used for the first asterisk, the second
for the next, and so on.

The second % indicates that what is to follow is the actual DATA to include,
or 'arguments'.

If you supply only ONE argument, it can be provided immediately. If you need
to supply more than one, you must enclose them together inside parentheses.

So what we have above is '%*.*f' for the formatting. This translates to
'print a floating point number with some arbitrary limit to the left and
right of the decimal'.  Looking at the arguments, we see that we will print
six digits to the left of the decimal, three to the right, and the number is
the third argument.  It translates to %6.3f.

You will find a full explanation of how the formatting works at
http://www.python.org/doc/current/lib/typesseq-strings.html (section 2.2.6.2
of the Python library reference).