Member-only story

F-string: Must have Python skill

Tomas Svojanovsky
4 min readJul 7, 2023

--

Strings are everywhere and easy to use. Every programmer will encounter strings. It’s inevitable. However, when it comes to string formatting, it can be challenging. It can easily become hard to read, or you may need to cast the type into a string.

What if I told you that your strings can be easy to read and you don’t need to use typecasting?

And that’s not all; f-strings can do much more.

Photo by Ricardo L on Unsplash

F-strings were introduced in Python 3.6. Both “f” and “F” can be the prefix for the f-string, and they mean formatted.

Classic problem

name = "Luna"
age = 3

# What we to get
Name: Homework; Urgency Level: 5

Option 1

pet = "Name: " + name + "; Age: " + str(age)
print(pet) # Name: Luna; Age: 3

There are two potential issues with the code creating the pet variable. First, it looks cumbersome and doesn’t read smoothly as we're dealing with multiple strings with each enclosed with quotation marks. Second, we must convert agege from int to str before it can be joined with other strings, further complicating the string concatenation operation.

Option 2

pet = "Name: {}; Age…

--

--

Tomas Svojanovsky
Tomas Svojanovsky

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet