Today we’ll be talking about string formatting with the format method and f-strings.
Strings often need formatting. There are a couple of ways we can format strings:
1) manual formatting
2) using the string format operator %
3) using the format method
4) using other string methods like center, ljust, rjust, zfill
5) using formatted string literals (f-strings)
Table of Contents
Manual Formatting
As for manual formatting, it’s the simplest, but also the most limited way of formatting text. Manual formatting is carried out by means of all the possible operations on strings like concatenation, repeating, using custom separators in the print function, etc. Here’s a simple example of manual formatting:
>>> a = "Here"
>>> b = "we"
>>> c = "go."
>>> print(a, b, c, " and again: ", a, b, c, sep = " <*> ")
Here <*> we <*> go. <*> and again: <*> Here <*> we <*> go.
The format Method
The format method and f-strings are much better solutions.
Let’s talk about the former first.
The format method takes two kinds of parameters: positional parameters and keyword parameters. There may be any number of the former as well as any number of the latter provided there is at least one parameter of any kind at all.
Positional parameters are accessed by index, keyword parameters are accessed by keyword.
The Syntax
The general syntax for the format method is as follows:
template.format(p0, p1, ..., k0 = v0, k1 = v1, ...)
The template is the string on which the method format should perform the formatting. The template contains format codes. Format codes are contained in curly braces. Format codes along with the enclosing curly braces may be referred to as format fields.
The parameters in the format method are the actual data which, after formatting, will be inserted into the template string in place of the format fields. The parameters p0, p1, … are positional parameters, the parameters k0, k1, … are the keywords of the keyword parameters with assigned values v0, v1, …
Positional Parameters
Complicated as it sounds, it gets much clearer after some examples are given. Let’s start with something simple, a template with just one format field and one positional parameter in the format method:
>>> text = "I like {} and baseball.".format("soccer")
>>> print(text)
I like soccer and baseball.
Here the format code within the curly braces is empty. We could also have more parameters and format fields:
>>> text = "They bought 5 {}, 3 {} and some {}.".format("apples", "bananas", "oranges")
>>> print(text)
They bought 5 apples, 3 bananas and some oranges.
If the format fields are empty, they just take the parameters in turn. If there are not enough parameters, we get an error:
>>> text = "They bought 5 {}, 3 {} and some {}.".format("apples", "bananas")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
Alternatively, we could use the indices of the positional parameters in the format fields for clarity. The indices are 0-based:
>>> text = "They bought 5 {0}, 3 {1} and some {2}.".format("apples", "bananas", "oranges")
>>> print(text)
They bought 5 apples, 3 bananas and some oranges.
The output is the same. But there’s another advantage (than just clarity) to using the indices: We can use them in any order and as many times as we want:
>>> text = '''
... They bought 5 {1}, 3 {2} and some {0}.
... The next day they bought even more {1},
... but not any {0} or {2}.
... '''.format("apples", "bananas", "oranges")
>>> print(text)
They bought 5 bananas, 3 oranges and some apples.
The next day they bought even more bananas,
but not any apples or oranges.
If we need to print the curly braces, we just have to double them:
>>> text = "They put the text in {} which look like so: {{}}".format("curly braces")
>>> print(text)
They put the text in curly braces which look like so: {}
Keyword Parameters
Now, how do we use keyword parameters? Let’s have a look:
>>> text = "Her name was {name}, she was {age} and was a {job}.".format(age = 45, name = "Lucinda", job = "musician")
>>> print(text)
Her name was Lucinda, she was 45 and was a musician.
So, we just use keywords, in any order.
We can also mix positional and keyword parameters. Positional parameters must always come first in the method:
>>> text = "He went to {0}, then to {1} and finally to {destination}.".format("Florida", "Georgia", destination = "Ohio")
>>> print(text)
He went to Florida, then to Georgia and finally to Ohio.
f-Strings
Finally, there are formatted string literals, aka f-strings. They use pretty much the same syntax as the format method, so we have format codes in curly braces embedded in the string. We prefix such strings with f:
>>> weight = 24
>>> f"Weight in kilograms: {weight}"
'Weight in kilograms: 24'
>>> f"Weight in grams: {weight * 1000}"
'Weight in grams: 24000'
>>> f"Amount of the substance in milligrams: {4.2784:>10.3f}"
'Amount of the substance in milligrams: 4.278'
In the last example you can see some more advanced formatting. We’ll discuss it in more detail in one of the future articles.
Here’s the video version of this article: