fstring vs format

Posted by Afsal on 25-Mar-2022

Hi Pythonistas!

Today we are going to compare the performance change between common string formatting techniques they are fstring and format method. Let us check this with an example.

Code

import timeit

hello = "hello"
world = "world"
python = "Python"
is_ = "is"
easy = "easy"

def using_f_string():
    string = f"{hello} {world} {python} {is_} {easy}"
    return string

def using_format():
    string = "{} {} {} {} {}".format(hello, world, python, is_, easy)
    return string

using_fstring_time = timeit.timeit(using_f_string, number=1000_1000)
using_format_time = timeit.timeit(using_format, number=1000_1000)
print("Time taken by fstring: ", using_fstring_time)
print("Time taken by format: ", using_format_time)

Output

Time taken by fstring: 1.4743069020000803

Time taken by format: 2.646669662000022

Why

If we analyze the internal of the format it involves a function call but in fstring, there is no function call. So fstring will be faster than the format method

Tip

Use fstring for formatting string if version of python >= 3.6

Hope you have learned from this blog. Please share your thoughts with afsal@parseltoungue.co.in