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”print(“Hello, “, name)result:"Hello, Annika"

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

name = “Annika”greeting = “Hello, %s.” % nameprint(greeting)result:“Hello, 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"print(“Hello, {}”.format(name))result: "Hello, Annika"

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

plan = {“name”:”Annika”,”activity”:”run”,”pet_name”:”Piper”}print(“Good Morning, {name}! Let’s go for a {activity} today with {pet_name}.”.format(**plan))result:"Good Morning, Annika! Let's go for a run today with 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”activity = “run”pet_name = “Piper”print(“Good Morning, {}! Let’s go for a {} today with {}.”.format(activity, pet_name, name)result:“Good Morning, run! Let’s go for a Piper today with 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}.”)result:“Good Morning, Annika! Let’s go for a run today with Piper.”

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

def shout(text):
return text.upper()
f"{shout(activity)}"result:
"RUN"

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.002892422489821911Using the format method: 0.006621009670197964Using the f-string: 0.0013131508603692055

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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store