F-Strings in Python

Say you want to combine display a multitude of variables in one print statement. How would you go about doing this?
Well, there are a couple of different options to choose from.
The first is concatenation, which gives us the correct output but is rather lengthy and cumbersome. Here is an example:
Desired output: I want to visit Hollywood on November 28 using a car.
place = "Hollywood"
date = "November 20"
vehicle = "car"
print("I want to visit " + place + " on " + date + " using a " + vehicle)
While the output is “I want to visit Hollywood on November 28 using a car” as desired, concatenation is quite tedious. Concatenation requires using the “+” in the print statement whenever the user wants to link a variable. For a lot of variables, this will be done a lot of times.
The second option is to use the format method. The format method can take in n number of parameters of strings. Here is an example:
Desired output: I want to visit Hollywood on November 28 using a car.
place = "Hollywood"
date = "November 20"
vehicle = "car"
print("I want to vist {place} on {date} using a {vehicle}".format(place, date, vehicle))
In this case, we again get the correct output. However, this again is quite tedious, and just lengthens the print statement even though it has greater readability than concatenation. To further understand what’s happening, let’s look at the print statement.
The print statement starts off with the text that we want displayed in the output and contains {}
which have the variable names inside of them. The string is then followed by .format()
; this is the format function which takes in any number of parameters and references the parameters to the {}
that contain the variables. In other words, the format function is referencing the parameters to the {}
in the string.
The final option is to use f-strings. F-strings by far are one of the most useful aspects of python, allowing users to increase code readability, be more consistent, and develop cleaner code. Here is an example:
Desired output: I want to visit Hollywood on November 28 using a car.
place = "Hollywood"
date = "November 20"
vehicle = "car"
print(f"I want to vist {place} on {date} using a {vehicle}".)
This print statement gets us our desired output in much cleaner and readable code.
Just like the format method, a f-string contains {}
which contain the desired variables and can display them regardless of whether they are integers, strings, etc.
Overall, f-strings prove to be far cleaner with greater code readability than the alternatives.
Thank you for reading until the end. Please consider following the writer and this publication. Visit Stackademic to find out more about how we are democratizing free programming education around the world.
If you liked this article then make sure to check out: