The % operator (modulo) can also be used for string formatting.
Given 'string' % values, instances of % in string are replaced with zero or more elements of values. This operation is commonly known as string interpolation.
>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.
>>> name = 'Bob'
>>> 'Hello, %s' % name
'Hello, Bob'
>>> name = 'Alice'
>>> age = 18
>>> 'My name is %s. I am %s.' % (name, age)
'My name is Alice. I am 18.'
Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}.
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
References:
1. Old String Formatting: % Operator
printf-style String Formatting
The
%
operator (modulo) can also be used for string formatting. Given'string' % values
, instances of%
instring
are replaced with zero or more elements ofvalues
. This operation is commonly known as string interpolation.2. The String format() Method: str.format()
str.format() >=Python 2.6
3. Formatted String Literals: f-strings
>= Python 3.6
Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with
f
orF
and writing expressions as{expression}
.