Article Thumbnail

Python's f-strings vs. str()

Comparing both approaches concerning execution time

Florian Dahlitz
2 min
Dec. 26, 2018

A few months ago I’ve seen a tweet from a Python learner with a code snippet containing f-strings. I asked, why she’s not using format() . She answered, that this is the new way of formatting strings. I was curious about it as I didn’t hear about it before. Seeing other people using it, I started to do it as well.

Two weeks ago I spotted a Pull Request on GitHub where somebody used f-strings to convert a value to a string as in the example below.

# Some more code above

val = 6
value = f"{val}"

# some more code

I was surprised by the usage of f-strings in this particular case. Another user commented to use str() instead. This conversation led me to the question, which one of both is faster as it was a computationally intensive piece of code.

Using boxx.timeit showed me the not irrelevant time difference.

from boxx import timeit


with timeit(name="f-strings"):
    for i in range(500_000):
        x = 6
        f"{x}"

with timeit(name="str"):
    for i in range(500_000):
        x = 6
str(x)
“f-strings” spend time: 0.08900404
"str” spend time: 0.160588

Wondering why this is the case? Looking at the byte code gives us the answer. Python provides a module for such cases, the Disassemble-Module. Let’s have a closer look at what’s happening.

import dis


def f_string(number: int):
    return f"{number}"


def str_string(number: int):
    return str(number)


print("============================== f-strings ==============================")
dis.dis(f_string)
print("================================ str() ================================")
dis.dis(str_string)

The result is shown below.

$ python disassemble_bytecode.py
============================== f-strings ==============================
  5           0 LOAD_FAST                0 (number)
              2 FORMAT_VALUE             0
              4 RETURN_VALUE
================================ str() ================================
  9           0 LOAD_GLOBAL              0 (str)
              2 LOAD_FAST                0 (number)
              4 CALL_FUNCTION            1
              6 RETURN_VALUE

As you can see the str_string method consists of one more command (CALL_FUNCTION). Function calls are expensive and f-strings don’t need to call a separate function.

To summarize f-strings are faster than str() in terms of converting integers and such types to string. But keep in mind, that we only had a look at simple types. How they perform on more complex types is currently out of my knowledge as I didn’t test it.


This post was originally published to Medium.