Image for post
Image for post

Python’s f-strings vs. str()

Florian Dahlitz
Dec 26, 2018 · 2 min read

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.

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.

“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.

The result is shown below.

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.

Feel free to leave a comment with your own thoughts. Stay curious and keep coding!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store