String Formatting
Contents
String Formatting#
The format
Method#
String objects have a format
method. This method allows for converting numbers and other data to strings.
a = 4
b = 5
c = a + b
nice_string = 'The result of {} plus {} is {}.'.format(a, b, c)
print(nice_string)
The result of 4 plus 5 is 9.
Calling the format
method of a string replaces all pairs {}
by the arguments passed to the format method. Next to integers also floats and strings can be passed to format
. The original string is not modified because it’s immutable. Instead, format
returns a new string object.
The arguments of format
can also be accessed by providing their index: the first argument has index 0, the second has index 1, and so on.
a = 4
b = a + a
print('The result of {0} plus {0} is {1}.'.format(a, b))
The result of 4 plus 4 is 8.
For more complex output (or more readable code) keyword arguments can be passed to format.
print('Mister {name} is {age} years old.'.format(name='Muller', age='42'))
Mister Muller is 42 years old.
Converting numbers to strings sometimes requires additional parameters: How many digits to use for floats? Shall numbers in several lines be aligned horizontally? There is a whole ‘mini language’ for writing formatting options. Here we provide only some examples. For details see Python documentation on format string syntax.
# print integer as float with 2 decimal places
print('The result is {:.2f}.'.format(3))
# right-align integers in fixed-width area
print('number of apples: {:3d}'.format(2))
print('number of oranges: {:3d}'.format(145))
# same works for floats and strings
print('percentage of apples: {:7.2f}'.format(2.1234))
print('percentage of oranges: {:7.2f}'.format(80.8976455))
print('percentage of bananas: {:7}'.format('unknown'))
The result is 3.00.
number of apples: 2
number of oranges: 145
percentage of apples: 2.12
percentage of oranges: 80.90
percentage of bananas: unknown
If indices or names are used for refering to format
’s arguments, they have to be placed on the left-hand side of the collon: {name:3.2f}
.
Formatted String Literals (f-Strings)#
Starting with version 3.6 of Python there is a more comfortable way to format strings. It’s very similar to formatting via format
method, but requires less code and increases readability. The two major differences are:
string literals have to be prefixed by
f
,the curly braces may contain a Python expression (an object name, for instance).
a = 123
print(f'Here you see {a}.')
b = 4.56789
print(f'Formatting works as above: {b:.2f} is a rounded float.')
Here you see 123.
Formatting works as above: 4.57 is a rounded float.
For details see formatted string literals in the Python documentation.