Member-only story

Which Python String Formatting to use?

Jayden Chua
4 min readNov 12, 2019

--

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.

  1. Formatting with the % operator
  2. Formatting with .format() method
  3. Using f-strings
  4. 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' %

--

--

Jayden Chua
Jayden Chua

Written by Jayden Chua

An avid web developer constantly looking for new web technologies to dabble in, more information can be found on bit.ly/jayden-chua

No responses yet