Python String Formatting

A synopsis of 4 different styles

Photo by Fabio Santaniello Bruun on Unsplash

When I was first learning to code, the typical beginner-level tutorial for inserting a variable into a print statement was pretty basic.

name = “Annika”

The next step in the journey of string formatting was to use the % s operator.

name = “Annika”

The % s operator is just a placeholder; it’s not very sophisticated or ideal to handle lots of complex components.

As I became more confident in my skills, I started using the format() method. For simple print statements, it worked well.

name = "Annika"

Additionally, the format method allows several variables to be passed in at once:

plan = {“name”:”Annika”,”activity”:”run”,”pet_name”:”Piper”}

However, it can be frustrating to keep everything straight as the number of variables increases and creates the potential for careless errors:

name= “Annika”

Although I didn’t give it much thought about how formatting could be better and easier, apparently there is a better way — the f-string (formatted string literal). Once I took the time to read about them and how to use them, I learned that the benefits are clear.

F-strings are less verbose than format() and faster. Using the same example as above:

print(f”Good Morning, {name}! Let’s go for a {activity} today with {pet_name}.”)

And, it’s possible to pass in a function to an f-string. That’s pretty exciting!

def shout(text):
return text.upper()

We can see how the use of f-strings makes code easier to read and reduces the potential for mistakes. For fun, let’s take a look at the difference in run times of the 3 different versions (omitting the first style since it is so rudimentary and not practical).

Code for comparing times of 3 methods

And the results:

Using the %s operator: 0.002892422489821911

In conclusion, the use of f-strings is indeed faster than using an % s operator and the format() method, easier to read, and makes code less susceptible to mistakes.