tags:

views:

246

answers:

6

Alex's answer has the following line when translated to English

print "%2d. %8.2f %8.2f %8.2f" % (    
            i, payment, interest, monthPayment)

I am unsure about the line

"%2d. %8.2f %8.2f %8.2f" %         #Why do we need the last % here?

It seems to mean the following

  1. apply %2d. to i
  2. apply %8.2f to payment
  3. apply %8.2f to interest
  4. apply %8.2f to monthPayment

The %-words seem to mean the following

  1. %2d.: a decimal presentation of two decimals

    2-4. %8.2f: a floating point presentation of two decimals

I am not sure why we use the 8 in %8.2f.

How do you understand the challenging line?

A: 

the %8.2f means allow 8 character spaces to hold the number given by the corrisponding variable holding a float, and then have decimal precision of 2.

Victor
+4  A: 

The last % is an operator that takes the string before it and the tuple after and applies the formatting as you note. See the Python tutorial for more details.

Kathy Van Stone
The '8' refers to the width of the floating point number
Kathy Van Stone
+1  A: 

The % is an operator which makes a format string. A simple example would be:

"%s is %s" % ( "Alice", "Happy" )

Which would evaluate to the string "Alice is Happy". The format string that is provided defines how the values you pass are put into the string; the syntax is available here. In short the d is "treat as a decimal number" and the 8.2 is "pad to 8 characters and round to 2 decimal places". In essence it looks like that format in particular is being used so that the answers line up when viewed with a monospace font. :)

In my code example the s means "treat as a string".

Calum
+7  A: 

The 8 in 8.2 is the width
"Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger"
The 2 is the number of decimal places

The final % just links the format string (in quotes) with the list of arguments (in brackets). It's a bit confusing that they chose a % to do this - there is probably some deep python reason.

edit: Apparently '%' is used simply because '%' is used inside the format - which is IMHO stupid and guaranteed to cause confusion. It's like requiring an extra dot at the end of a floating point number to show that it's floating point!

Martin Beckett
@all: What is the reason for that we have to use % for formatting?
Masi
@masi: Please read: http://docs.python.org/library/stdtypes.html#string-formatting-operations
S.Lott
You don't have to use %... That's just the most common way. The % refers to the %s style printf syntax. The % operator on strings is just a handy sprintf. You can also use the Template module: http://www.python.org/doc/2.5.2/lib/node40.html
Jim Carroll
Largely because print is a builtin rather than a function call - which is fixed in python 3.0. It's just a little unfortunate that is was necessary to use "%" which is confusing for new users and doesn't give a very helpfull error if you miss it out.
Martin Beckett
@mgb: It's absolutely nothing to do with whether print is a statement or a function and it wasn't "necessary". If neither variety of print existed in the language (use sys.stdout.write() instead), the problems with % would still exist.
John Machin
If it was a function call there would just be two parameters, the format string and the list of arguements. There would be no need for an extra magic character.
Martin Beckett
+1  A: 

The % after a string tells Python to attempt to fill in the variables on the left side of the '%' operator with the items in the list on the right side of the '%' operator.

The '%' operator knows to find the variable in the string by looking for character in the string starting with %.

Your confusion is that you think the % operator and the % character in the string are the same.

Try to look at it this way, outside a string % is an operator, inside a string it is possibly a template for substitution.

Martin P. Hellwig
+1  A: 

As usual, a quote of the doc is required - string-formatting:

String and Unicode objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf in the C language.

And the description of the conversion specifier to explain %8.2f

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

  1. The '%' character, which marks the start of the specifier.
  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
  3. Conversion flags (optional), which affect the result of some conversion types.
  4. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
  5. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
  6. Length modifier (optional).
  7. Conversion type.

When the right argument is a dictionary (or other mapping type), the format string includes mapping keys (2). Breaking the example to 2 steps, we have a dictionary and a format that includes keys from the dictionary (the # is a key):

>>> mydict = {'language':'python', '#':2}
>>> '%(language)s has %(#)03d quote types.' % mydict
'python has 002 quote types.'
>>>
gimel
@gimel: Could you give an example of mapping key. The docs has the following line: %(language)s has %(#)03d quote types. --- What do they mean with the following "%(language)s has"?
Masi
Added a 2-step version of the example.
gimel