Member-only story
F-string: Must have Python skill
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.
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 age
ge from int
to str
before it can be joined with other strings, further complicating the string concatenation operation.
Option 2
pet = "Name: {}; Age…