next up previous contents
Next: Using Names in Format Up: Input and Output Previous: The print command   Contents


Formatting Strings

In python, string formatting is performed through overloading of the percent operator (%) for string values. On the left hand side of the operator, you provide a string which is a combination of literal text and formatting codes. Each appearance of a formatting code is matched with an object in a tuple, which appears on the right hand side of the percent sign. The resultant string (which is suitable for printing) replaces the formatting codes with formatted versions of the objects in the tuple. A brief description of the formatting codes is shown in Table 5.2. The formatting codes are preceded with a percent sign, and, optionally, a number which indicates the number of columns which should be used to format the value. For floating point numeric values, the percent sign can optionally be followed by two numbers separated by a period (.); in this case the first number is the field width, and the second number is the number of digits to display after the decimal point. For example, to produce a string called fstring which contains the number 7, formatted with three zeroes after the decimal point, we could use a statement like the following:
>>> fstring = 'The number is %5.3f' % (7)
>>> fstring
'The number is 7.000'
Notice that the field width was specified as 5, because it needs to be wide enough to display the number along with the decimal point.


Table 5.1: Formatting Codes
Code Meaning
d or i Decimal Integer
u Unsigned Integer
o Octal Integer
h or H Hexadecimal Integer
f Floating Point Number
e or E Floating Point Number: Exponential Notation
g or G Floating Point Number: ``Optimal'' Notation
s String value - also provides string representation of any object
c Single character
% Literal percent sign


The %g and %G formatting codes will use normal notation when the exponent of a number is greater than -4, and the specified width is sufficient to display the number. If either of these conditions is not true, then exponential notation will be used.

The right hand argument to the percent sign must contain a tuple, although parentheses are not strictly required when there is exactly one argument to be formatted. With multiple items to be formatted, the format specifications and values are matched one-to-one.

>>> print '%d items at %5.2f per item gives a total of $%4.2f' % \
... (7,.29,7 * .29)
7 items at  0.29 per item gives a total of $2.03
If you fail to provide the proper number of arguments to be converted, a TypeError is raised.


next up previous contents
Next: Using Names in Format Up: Input and Output Previous: The print command   Contents
Phil Spector 2003-11-12