Member-only story
Which Python String Formatting to use?
Here are my go-to steps to decide which python string formatting to use.
Overview
There are different ways to format strings in Python. I quickly summarize the different methods here. You should dig deeper to see how these techniques can be used in your respective scenarios.
- Formatting with the % operator
- Formatting with .format() method
- Using f-strings
- Using Template strings
Method 1: Formatting with % operator
Here’s one of the oldest method among the four techniques described above. Included here only so we know it exists and when we come across it in older legacy or Python 2.6 code, we understand it is doing string formatting. It is also sometimes known as C-style formatting.
Examples
# Setups up variables we can use later in the example
>>> species = 'versicolor'
>>> petal_length = 13.498# Example 1: Basic string substitution
>>> 'The species is %s' % species# Outputs
The species is versicolor---# Example 2: Basic float formatting with 2 decimal places accuracy
>>> 'The petal length is %.2f mm' %…