Skip to content

Instantly share code, notes, and snippets.

@ofelix03
Created March 2, 2021 13:50
Show Gist options
  • Save ofelix03/adedf35979f28b860110598247fd87e4 to your computer and use it in GitHub Desktop.
Save ofelix03/adedf35979f28b860110598247fd87e4 to your computer and use it in GitHub Desktop.
Comparing execution speed of interpolation methods
import timeit
def test_f_string():
first_name = "Felix"
last_name = "Otoo"
middle_name = "Albert"
age = 28
profession = "Software Engineer"
f"This is {first_name} {middle_name} {last_name}. He is {age} years old. He is a {profession}"
def test_mudulose_string():
first_name = "Felix"
last_name = "Otoo"
middle_name = "Albert"
age = 28
profession = "Software Engineer"
"This is %(first_name)s %(middle_name)s %(last_name)s. He is %(age)s years old. He is a %(profession)s" %{"first_name": first_name, "middle_name": middle_name, "last_name": last_name, "age": age, "profession": profession}
def test_str_format_string():
first_name = "Felix"
last_name = "Otoo"
middle_name = "Albert"
age = 28
profession = "Software Engineer"
"This is {first_name} {middle_name} {last_name}. He is {age} years old. He is a {profession}".format(first_name=first_name, middle_name=middle_name, last_name=last_name, age=age, profession=profession)
t = timeit.Timer(test_f_string)
print('f-strings =', t.timeit())
t3 = timeit.Timer(test_str_format_string)
print('Str.format() = ', t3.timeit())
t2 = timeit.Timer(test_mudulose_string)
print('modulos-oeprator =', t2.timeit())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment