Unable to understand a line of Python code exactly

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?

Upvotes: 1

Views: 2165

Answers (6)

Martin Beckett
Martin Beckett

Reputation: 96119

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!

Upvotes: 7

gimel
gimel

Reputation: 86344

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.'
>>> 

Upvotes: 1

Martin P. Hellwig
Martin P. Hellwig

Reputation: 730

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.

Upvotes: 1

Victor
Victor

Reputation: 5807

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.

Upvotes: 0

Calum
Calum

Reputation: 5926

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".

Upvotes: 1

Kathy Van Stone
Kathy Van Stone

Reputation: 26271

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.

Upvotes: 4

Related Questions