You are currently viewing F-String In Python – A Modern Way To Perform String Interpolation

F-String In Python – A Modern Way To Perform String Interpolation

String interpolation can be performed using multiple ways in Python. There are several methods provided by Python that can help us interpolate strings. Some of them are known as an old school or traditional way of formatting the string and some are added recently been added and gained so much popularity.

One of the modern ways of interpolating the strings in Python is called f-string. First of all, what is string interpolation? String interpolation can be defined as assessing the string literal that contains one or more placeholders and replacing the placeholders with the corresponding values.

f-string was introduced in Python version 3.6 and proposed in the PEP 498 to make the string formatting easier and easy to read. This improved the way how a string is formatted.

f-string

f-string is also called Formatted String literal and is a convenient way to interpolate variables into the string. Unlike the other formatting methods that use the % operator and .format() method, the f-strings are prefixed with the letter f with the curly braces containing expressions that will be replaced by the corresponding values.

The f in f-string can also stand for fast because of its better performance than the other formatting methods and it has several advantages.

Advantages

The big advantages of using f-strings are listed below:

  1. Readability: F-strings are easier to read and write compared to other string formatting methods, such as the % operator and the .format() method. They allow us to include variables and expressions directly in the string literal, which makes the code more concise and expressive.
  2. Flexibility: F-strings offer more flexibility and control over the formatting of interpolated values. We can specify a format specifier after the variable or expression in the curly braces to control how the value is formatted.
  3. Performance: F-strings are faster than the .format() method and the % operator.

Syntax

The syntax of the f-string is very simple.

The above example shows the usage of f-string where the string literal has the letter f at the beginning with the placeholders containing expressions.

Using expressions

The values are evaluated at the runtime in f-string, so we can put valid arbitrary expressions inside them.

The above code was executed without any error and printed the value of 2 raised to power 3.

Like this, we can use the user-defined functions inside the f-string. Here’s the example

The function named add() was called inside the f-string that adds the exp argument with 'python' and prints it.

Using methods

We can call Python methods directly inside the f-string. The following example will show you calling the methods directly inside the f-string.

In the above code, the upper() method was called directly inside the f-string.

Using f-string inside Python classes

Classes in Python are used in OOPs (Object Oriented Programming) and we can use objects created from classes with f-string. Here’s an example below demonstrating the use of f-string inside a Python class.

Now we can call the class Detail with the arguments. Here’s how we can do it.

In the class Detail, the __str__ method is used for the presentation of the objects as a string and __str__ is the informal presentation of the string. We could even use __repr__ to print the objects as the official representation of the string.

Well, you could have noticed that !r is used inside the f-string to print the __repr__ object. It is because !r chooses the repr method to format the object.

Using multiline f-string

We can use multiple f-string in a single statement. Take a look at the example below.

But there is a flaw in using multiline f-string, we have to place f at the beginning of each string when writing multiline f-strings. If we try to do so then we’ll get something like the below.

Escape sequences

We cannot use backlashes inside the f-string to escape the quotation mark and all, if we try to do it, we’ll get an error.

There is a way to escape quotation marks by using different types of quotes inside the expression.

Braces

If we want to include braces in our code then we should use extra braces to the string literal in order to appear in the output.

In the first block of code, we used two pairs of braces and we got the output with the braces whereas, in the second block of code, we used a single pair of braces and we didn’t get the expected output instead we got the whole expression as it is in the f-string.

Using format specifiers

We can use format specifiers to evaluate the expression inside the f-string. The following example demonstrates the usage of floating-point precision inside the f-string.

Dictionaries

We have seen the direction to use quotation marks inside an f-string, but we need to be more careful when using the dictionary inside an f-string.

The above code works because we used different types of quotation marks but if we use the same type of quotation marks then we’ll get an error.

Using inline comments

Expressions inside the f-strings cannot contain comments using the # symbol, we’ll get an error.

Comparing the speed

As mentioned earlier, the f-strings are much faster than the other formatting methods. We can say that the letter f in f-string stands for “fast“.

Here’s a speed comparison among f-string% formatting and .format method.

%(modulo) operator formatting

str.format() method

f-string

We can clearly see the differences in the time of execution of the code for different formatting methods. Thus, we can conclude that the f-string took less time to execute the code than the other formatting methods.

Conclusion

In this article, we learned about the f-string and its usage in the code. F-string is an improved and modern way to interpolate the string.

F-string reduces the mess in the code and increases the readability of the code and provides flexibility and control over the formatted string literal.


🏆Other articles you might like if you like this article

Integrate PostgreSQL database with Python and perform CRUD operations.

Display static and dynamic images on the frontend using Flask.

Tackle the shortage of data with data augmentation techniques.

8 Different ways you can reverse a Python list.

Scrape the data from the website using BeautifulSoup in Python.


That’s all for now

Keep Coding✌✌