Python Tutorial_ Formatted Output
Python Tutorial_ Formatted Output
Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact
Formatted Output
Output
Data Protection
Declaration
In computer scienc,
output is seen as the
Data Protection
information produced
Declaration
by a computer
program. The output
can be perceived by
the user.
Formatting
Formatting in
computer science is a
method of arranging
data for storage or
display.
This website is
supported by:
Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Obsolete and equivalent to 'd', i.e. signed integer decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.
The following examples show some example cases of the conversion rules from the table above:
Flag Meaning
# Used with o, x or X specifiers the value is preceded with 0, 0o, 0O, 0x or 0X respectively.
0 The conversion result will be zero padded for numeric values.
- The converted value is left adjusted
If no sign (minus sign e.g.) is going to be written, a blank space is inserted before the value.
+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).
Examples:
Even though it may look so, the formatting is not part of the print function. If you have a closer look at our examples, you will see that we passed a formatted string to the print function. Or to put it in other words:
If the string modulo operator is applied to a string, it returns a string. This string in turn is passed in our examples to the print function. So, we could have used the string modulo functionality of Python in a two
layer approach as well, i.e. first create a formatted string, which will be assigned to a variable and this variable is passed to the print function:
The Python help function is not very helpful concerning the string format method. All it says is this:
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
Let's dive into this topic a little bit deeper: The format method was added in Python 2.6. The general form of this method looks like this:
The template (or format string) is a string which contains one or more format codes (fields to be replaced) embedded in constant text. The "fields to be replaced" are surrounded by curly braces {}. The curly braces
and the "code" inside will be substituted with a formatted value from one of the arguments, according to the rules which we will specify soon. Anything else, which is not contained in curly braces will be literally
printed, i.e. without any changes. If a brace character has to be printed, it has to be escaped by doubling it: {{ and }}.
There are two kinds of arguments for the .format() method. The list of arguments starts with zero or more positional arguments (p0, p1, ...), it may be followed by zero or more keyword arguments of the form
name=value.
A positional parameter of the format method can be accessed by placing the index of the parameter after the opening brace, e.g. {0} accesses the first parameter, {1} the second one and so on. The index inside of
the curly braces can be followed by a colon and a format string, which is similar to the notation of the string modulo, which we had discussed in the beginning of the chapter of our tutorial, e.g. {0:5d}
If the positional parameters are used in the order in which they are written, the positional argument specifiers inside of the braces can be omitted, so '{} {} {}' corresponds to '{0} {1} {2}'. But they are needed, if
you want to access them in different orders: '{2} {1} {0}'.
The following diagram with an example usage depicts how the string method "format" works works for positional parameters:
In the following example we demonstrate how keyword parameters can be used with the format method:
It's possible to left or right justify data with the format method. To this end, we can precede the formatting with a "<" (left justify) or ">" (right justify). We demonstrate this with the following examples:
Option Meaning
'<' The field will be left-aligned within the available space. This is usually the default for strings.
'>' The field will be right-aligned within the available space. This is the default for numbers.
'0' If the width field is preceded by a zero ('0') character, sign-aware zero-padding for numeric types will be enabled.
>>> x = 378
>>> print("The value is {:06d}".format(x))
The value is 000378
>>> x = -378
>>> print("The value is {:06d}".format(x))
The value is -00378
',' This option signals the use of a comma for a thousands separator.
'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form "+000000120". This alignment option is only valid for numeric
types.
'^' Forces the field to be centered within the available space.
Unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the alignment option has no meaning in this case.
Additionally, we can modify the formatting with the sign option, which is only valid for number types:
Option Meaning
'+' indicates that a sign should be used for both positive as well as negative numbers.
'-' indicates that a sign should be used only for negative numbers, which is the default behavior.
space indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.
We have seen in the previous chapters that we have two ways to access the values to be formatted:
Just to mention it once more: We could have used empty curly braces in the previous example!
Using keyword parameters:
The second case can be expressed with a dictionary as well, as we can see in the following code:
The double "*" in front of data turns data automatically into the form 'province="Ontario",capital="Toronto"'. Let's look at the following Python program:
$ python3 country_capitals.py
Countries and their capitals:
United States: Washington
Canada: Ottawa
Austria: Vienna
Netherlands: Amsterdam
Germany: Berlin
UK: London
Switzerland: Bern
England: London
US: Washington
France: Paris
We can rewrite the previous example by using the dictionary directly. The output will be the same:
"locals" is a function, which returns a dictionary with the current scope's local variables, i.e- the local variable names are the keys of this dictionary and the corresponding values are the values of these variables:
>>> a = 42
>>> b = 47
>>> def f(): return 42
...
>>> locals()
{'a': 42, 'b': 47, 'f': <function f at 0xb718ca6c>, '__builtins__': <module 'builtins' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}
>>>
The dictionary returned by locals() can be used as a parameter of the string format method. This way we can use all the local variable names inside of a format string.
Continuing with the previous example, we can create the following output, in which we use the local variables a, b and f:
The string class contains further methods, which can be used for formatting purposes as well: ljust, rjust, center and zfill
center(...):
Return S centred in a string of length width. Padding is done using the specified fill character. The default value is a space.
Examples:
>>> s = "Python"
>>> s.center(10)
' Python '
>>> s.center(10,"*")
'**Python**'
ljust(...):
Return S left-justified in a string of length "width". Padding is done using the specified fill character. If none is given, a space will be used as default.
Examples:
>>> s = "Training"
>>> s.ljust(12)
'Training '
>>> s.ljust(12,":")
'Training::::'
>>>
rjust(...):
Return S right-justified in a string of length width. Padding is done using the specified fill character. The default value is again a space.
Examples:
>>> s = "Programming"
>>> s.rjust(15)
' Programming'
>>> s.rjust(15, "~")
'~~~~Programming'
>>>
zfill(...):
Pad a string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. This method can be easily emulated with rjust.
Examples:
Python 3.6 introduces formatted string literals. They are prefixed with an 'f'. The formatting syntax is similar to the format strings accepted by str.format(). Like the format string of format method, they contain
replacement fields formed with curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format() protocol. It's easiest to understand by looking at the
following examples:
© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein