In this article, we will talk about f-strings and their advantages over regular traditional string formatting in python.
F-strings have been introduced in Python 3.6 and allow for easier and more convenient formatting. The syntax to define an f-string is almost identical to defining the string itself. You use quotes but proceed the opening quote part with the lower case ‘f’ or upper case ‘F’. Below there are a few examples.
As with normal string definition, you can use single quotes:
my_first_f_string = f’I am going to use f-strings form now on.’ Or double quotes:
f_string_with_double_qoutes = F”I am going to use f-strings form now on.”
Or triple quotes for f-strings spanning across multiple lines:
multiline_f_string = f”’first line second line”’
But what are the advantages of the f-strings? The next section will explain the old way to format strings and why f-strings are better.
The old way
Do you remember when you have learned about strings? You probably have defined a function hello_world similar to the code below:
def hello_world(): print(“Hello, world!”)
And then you progressed to write a function that could greet not the whole world but a particular person. Something similar to the definition below:
def hello_world(name): print(“Hello, ” + name + “!”) Or even better-formatted version below:
def hello_world(name): print(“Hello, {}!”.format(name))
F-strings offer another, even simpler, and even more readable version of the function above. Below we redefine the function using f-strings.
def hello_world(name): print(f”Hello, {name}!”) As you can see the string is proceeded by the letter f and the variable name that needs to be inserted in the string is enclosed by curly brackets { }. No need for the .format() function anymore.
Flexible replacement for the variables
As you have noticed from the previous section f-strings allow for the elegant replacement of the variables in the strings. F-strings are not only a more elegant way of doing string formatting but are they are also faster than other formatting methods. The expressions inside the curly brackets are evaluated at a run time and at that point they are added to the rest of the string.
In the previous section, we saw an example of interpolating a string (name variable) within another string. Note that f-strings can be used to interpolate any standard python data type within a string so we could use integers, floats, lists, or dictionaries.
Let’s have a look at some examples.
Incorporating integers and floats within a f-string
height = 176 weight = 123.3 info = f’I am {height} cm heigh and I weigh {weight} kilograms.’
Incorporating lists within a f-string
grocery_list = [‘apples’, ‘oranges’, ‘kiwis’]
message = f’I need to get {grocery_list} from the market.’
Incorporating dictionaries within a f-string
student_grades = {'Ana': ['A', 'B'], 'Bart': ['A', 'A'] }
message = f'This semester grades are {student_grades}.'
Incorporating whole expressions within a f-string
Not only can f-strings incorporate variables but also whole expressions. Therefore we could incorporate the area of the square within a sentence describing the square only knowing the length of its side.
side_length = 5 message = f’Square area is {side_length * side_length}.’ The expression 5*5 is evaluated at the run time and 25 is interpolated in the right place of the sentence.
Creating string representation for the objects
It is common to create a string representation for the objects that we are defining in the python modules with __str__() . Using f-strings to do it makes the code more readable. Here there is an example of the car class.
class Car: def __init__(self, color, mileage): self.color = color self.mileage = mileage def __str__(self): return f’I am a {self.color} car that has {self.mileage} miles.’
Note that we have used an f-string to define the string representation of the car object. Let’s now create a car and call print() function with the car as a parameter.
car = Car(‘red’, 100000) print(car)
The print function has returned a nicely formatted string representation of our car.
Multiple line f-strings
Another usage of f-strings would be using them with strings that span over multiple lines of code. This works exactly the same way as single-line strings except that the string needs to be in triple quotes.
Below we have an example of the book description that spans over two lines.
title = “Gone with the wind” author = “Margaret Mitchell” book_description = f”’| Title: {title} | | Author: {author} |”’ Let’s print the book_desciption variable.
print(book_description)
We are getting nicely formatted book details.
Summary
In this article, you have learned about f-strings and have been exposed to examples illustrating how to use them. You should now understand why it is better to use f-string than traditional python string formatting methods.
If you are not using f-strings yet, it is time to start now…
Happy coding!