Python:Format Printing
Jump to navigation
Jump to search
The %
operator provides a powerful and succinct mechanism for solving many formatting problems.
The print method
The % operator takes a formatting string followed by one argument or a tuple of arguments. The formatting string includes a number of escape sequences - each of these is substituted by the actual parameter given.
%s is used when a string is expected %d is used when an integer (or long) is expected %f is used when a floating point number is expected
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]
Using % to align
We can format output involving fixed and variable components. Usually we align strings to the left and numbers to the right.
In the %
a number of values may follow the % operator.
These values are used up by %
placeholders in the format string.
"Country: %-18s GDP: %20d"
%-18s
- the minus in
-18
means align left,
- the minus in
the 18
means 18 characters
are to be used, the s
is for string.
%20d
- the 20 means use 20 characters and align right, d is for decimal.
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]