f-string: Improved and Modern Way Of String Formatting

Valentsea
Total
0
Shares

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.

There are 4 ways to perform string formatting:
% Operator (“old style”)
format() string method
String literals (f-string)
String Template Class

favicon
geekpython.in



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:

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.

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.

Performance: F-strings are faster than the .format() method and the % operator.



Syntax

The syntax of the f-string is very simple.

var1 = "Geeks"
var2 = "GeekPython"

f"Hey, there {var1}, Welcome to {var2}."

----
Hey, there Geeks, Welcome to GeekPython.
Enter fullscreen mode

Exit fullscreen mode

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.

import math
exp = f'{math.pow(2, 3)}'
print(exp)

>>> 8.0
Enter fullscreen mode

Exit fullscreen mode

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

def add(exp):
    return exp + 'python'

val = 'geek'
str = f'{add(val)}'
print(str)

>>> geekpython
Enter fullscreen mode

Exit fullscreen mode

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.

val = 'geekpython'
str = f'{val.upper()}'
print(str)

>>> GEEKPYTHON
Enter fullscreen mode

Exit fullscreen mode

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.

class Detail:
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname

    def __str__(self):
        return f'Hello from {self.firstname} {self.lastname}'
Enter fullscreen mode

Exit fullscreen mode

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

detail = Detail('Geek', 'Python')
print(f'{detail}')

>>> Hello from Geek Python
Enter fullscreen mode

Exit fullscreen mode

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.

    def __repr__(self):
        return f'Good bye from {self.firstname} {self.lastname}'

print(f'{detail!r}')

>>> Good bye from Geek Python
Enter fullscreen mode

Exit fullscreen mode

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.

real_name = 'Robert Downey Jr'
reel_name = 'Tony Stark'
hero_name = 'Iron Man'

details = (
    f'The real name is {real_name}, '
    f'The reel name is {reel_name}, '
    f'The hero name is {hero_name}.'
)
print(details)

>>> The real name is Robert Downey Jr, The reel name is Tony Stark, The hero name is Iron Man.
Enter fullscreen mode

Exit fullscreen mode

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.

real_name = 'Robert Downey Jr'
reel_name = 'Tony Stark'
hero_name = 'Iron Man'

details = (
    f'The real name is {real_name}, '
    'The reel name is {reel_name}, '
    'The hero name is {hero_name}.'
)
print(details)

>>> The real name is Robert Downey Jr, The reel name is {reel_name}, The hero name is {hero_name}.
Enter fullscreen mode

Exit fullscreen mode



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.

val = f'{'hello'}'
print(val)

>>> SyntaxError: f-string expression part cannot include a backslash
Enter fullscreen mode

Exit fullscreen mode

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

val = f"{'hello'}"
print(val)

>>> hello
Enter fullscreen mode

Exit fullscreen mode



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.

val = f'{{{4**2}}}'
print(val)

>>> {16}

val1 = f'{{2 ** 2 * 4}}'
print(val1)

>>> {2**2*4}
Enter fullscreen mode

Exit fullscreen mode

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.

import math

value = math.pi
width = 5
precision = 10

val = f'result: {value:{width}.{precision}}'
print(val)

>>> result: 3.141592654
Enter fullscreen mode

Exit fullscreen mode



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.

greet = {'expression': 'Hello', 'from': 'GeekPython'}

my_dict = f'{greet["from"]} is saying {greet["expression"]}.'
print(my_dict)

>>> GeekPython is saying Hello.
Enter fullscreen mode

Exit fullscreen mode

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.

greet = {'expression': 'Hello', 'from': 'GeekPython'}

my_dict = f'{greet['from']} is saying {greet['expression']}.'
print(my_dict)

>>> SyntaxError: f-string: unmatched '['
Enter fullscreen mode

Exit fullscreen mode



Using inline comments

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

name = 'geeks'
print(f'Hey there, {name #this is a comment}')

>>> SyntaxError: f-string expression part cannot include '#'
Enter fullscreen mode

Exit fullscreen mode



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

import timeit

duration_mod = timeit.timeit("""name = 'RDJ'
hero = 'Iron Man'
'%s plays the role of %s.' % (name, hero)""", number=10000)
print(duration_mod)

>>> 0.00748830009251833
Enter fullscreen mode

Exit fullscreen mode

str.format() method

import timeit

duration_format = timeit.timeit("""name = 'RDJ'
hero = 'Iron Man'
'{} plays the role of {}.' .format(name, hero)""", number=10000)
print(duration_format)

>>> 0.009640300180763006
Enter fullscreen mode

Exit fullscreen mode

f-string

import timeit

duration_fstring = timeit.timeit("""name = 'RDJ' 
hero = 'Iron Man'
f'{name} plays the role of {hero}.'""", number=10000)
print(duration_fstring)

>>> 0.0016423999331891537
Enter fullscreen mode

Exit fullscreen mode

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✌✌

Total
0
Shares
Valentsea

How to use Linode Object Storage with Laravel

What is Linode Object storage? Linode Object Storage is a highly available S3 compatible object storage.It is used…

You May Also Like