Contents
Introduction
There exist at least 5 ways to format/interpolate strings in Python. While it was common to see “(manual) string concatenation” and “printf Style” formatting until 2019/2020, it was followed by “str.format” which seems to get replaced by “f-strings” nowadays. Furthermore, the string library provides “template strings”. To make a long story short: when it comes to string formatting, just use something but here are some examples how each of them looks like ;).
String Concatenation
Belive it or not but strings can be formatted and concatenated manually. The example below matches the output of the printf style example.
print('width := '+str(round(9.87654321,2)))
print('width := '+str(round(9.87654321,3)))
printf Style
The classical way for interpolating strings when programming Python is similar to string interpolation with C when using printf:
printf("width := %.2f \n", 9.87654321);
printf("width := %.3f \n", 9.87654321);
outputs:
width := 9.88
width := 9.877
Python string interpolation using the %
operator looks like this:
print('width := %.2f' % 9.87654321)
print('width := %.3f' % 9.87654321)
yields the same result:
width := 9.88
width := 9.877
Some samples for integers look like this:
number = 0x5A
print('as char: %c (ASCII)' % number)
print('decimal: %d' % number)
print('octal: %o' % number)
print('hex: %X' % number)
outputs:
as char: Z (ASCII)
decimal: 90
octal: 132
hex: 5A
Using multiple variables looks like this:
number = 0x5A
string_0 = 'certificate'
print('The %s expires after %d days.' % (string_0, number))
The certificate expires after 90 days.
The list of valid format specifiers (%
) can be found here.
str.format
The floating point example would look like this:
print('width := {:.2f}'.format(9.87654321))
print('width := {:.3f}'.format(9.87654321))
width := 9.88
width := 9.877
str.format
can be used with multiple input variables as well. It supports different methods to interpolate a string with multiple variables:
number = 0x5A
string_0 = 'certificate'
named_vars = {'number':0x5A, 'string_0':'certificate'}
print('The {} expires after {} days.'.format(string_0, number))
print('The {0} expires after {1} days.'.format(string_0, number))
print('The {1} expires after {0} days.'.format(number, string_0))
print('The {string_0} expires after {number} days.'.format(\
string_0=string_0, number=number))
print('The {string_0} expires after {number} days.'.format(**named_vars))
The certificate expires after 90 days.
The certificate expires after 90 days.
The certificate expires after 90 days.
The certificate expires after 90 days.
The certificate expires after 90 days.
Using str.format
might be the most versatile with respect to all classes/objects Python provides.
f-Strings
Internally f-strings do something similar as described in the string concatenation section which also implies that functions and operations within the bounds of curly braces is evaluated first before converted to a string. f-strings stand for “formatted strings” but since it is a bit faster than other approaches we may call it “fast strings” as well ;).
A slightly modified example of a floating point number looks like this:
number = 8.87654321
print(f'width := {1+number:#.2f}')
print(f'width := {1+number:#.3f}')
width := 9.88
width := 9.877
The other example looks like this when using f-strings:
number = 0x5A
string_0 = 'certificate'
print(f'The {string_0} expires after {number} days.')
The certificate expires after 90 days.
Template Strings
Last but not least there do exist template strings. This might be actually the least common approach to format strings. In fact it aims at substituting (sub)substrings/placeholders and therefore don’t allow for string formatting as shown in the other examples.
Templates need to be imported first :
from string import Template
A floating point example would look like this. However, if the number should be rounded to x decimal numbers it would need to be done manually:
number = 9.87654321
template = Template('width := ${number}')
string_out_0 = template.substitute(number=number)
string_out_1 = template.substitute(number=round(number,2))
string_out_2 = template.substitute(number=round(number,3))
print(string_out_0)
print(string_out_1)
print(string_out_2)
width := 9.87654321
number = 9.87654321
template = Template('width := ${number}')
string_out_0 = template.substitute(number=number)
string_out_1 = template.substitute(number=round(number,2))
string_out_2 = template.substitute(number=round(number,3))
print(string_out_0)
print(string_out_1)
print(string_out_2)
The string substitution example looks like this:
number = 0x5A
string_0 = 'certificate'
template = Template('The ${string_0} expires after ${number} days.')
string_out_0 = template.substitute(number=number, string_0=string_0)
print(string_out_0)
The certificate expires after 90 days.