Python Shorts
How and Why to use f strings in Python3
A simple guide to use the new functionality in Python 3
Python provides us with many styles of coding.
And with time, Python has regularly come up with new coding standards and tools that adhere even more to the coding standards in the Zen of Python.
Beautiful is better than ugly.
In this series of posts named Python Shorts, I will explain some simple but very useful constructs provided by Python, some essential tips, and some use cases I come up with regularly in my Data Science work.
This post is specifically about using f strings in Python that was introduced in Python 3.6.
3 Common Ways of Printing:
Let me explain this with a simple example. Suppose you have some variables, and you want to print them within a statement.
name = 'Andy'
age = 20
print(?)
----------------------------------------------------------------
Output: I am Andy. I am 20 years old
You can do this in various ways:
a) Concatenate: A very naive way to do is to simply use +
for concatenation within the print function. But that is clumsy. We would need to convert our numeric variables to string and keep care of the spaces while concatenating. And it doesn’t look good as the code readability suffers a little when we use it.
name = 'Andy'
age = 20
print("I am " + name + ". I am " + str(age) + " years old")
----------------------------------------------------------------
I am Andy. I am 20 years old
b) % Format: The second option is to use %
formatting. But it also has its problems. For one, it is not readable. You would need to look at the first %s
and try to find the corresponding variable in the list at the end. And imagine if you have a long list of variables that you may want to print.
print("I am %s. I am %s years old" % (name, age))