Member-only story

Formatted Strings in Python — The Best Way Vs Outdated Ways

Liu Zuo Lin
4 min readNov 7, 2021

--

As Python beginners, we were probably taught that strings cannot be added together with integers or floats — if we wanted to add a number into a string, we had to first cast that number into a string using str(). If we have taken slightly higher-level intermediate classes, we might have been introduced to formatted strings where we wouldn’t need to convert numbers into strings and so on. I’ve tutored a couple of students who unfortunately have been taught the old-fashioned and more annoying way of writing formatted strings, and thus, here’s this article if you’re unfortunately one of them!

A Simple String Problem in Python

Let’s say we have a string variable name and an integer variable age

name = "bob"
age = 25

And we wish to create the following string:

"hi my name is bob, and my age is 25"

If we don’t use formatted strings, we might write our code like this:

string = "hi my name is " + name + ", and my age is " + str(age)

Different Ways to Use Formatted Strings in Python

There are multiple ways to write formatted strings in Python (new and old), and here they are:

--

--

Liu Zuo Lin
Liu Zuo Lin

Written by Liu Zuo Lin

SWE @ Meta | [Ebook] 101 Things I Never Knew About Python: https://payhip.com/b/vywcf

No responses yet