10 ms·
f-strings are also the fastest way to format a string in Python from what I've seen. $ python3.12 -m timeit 'f"Welcome to {2 ** 3}."' 5000000 loops, best o
by Hamuko 3y ago
f-strings are also the fastest way to format a string in Python from what I've seen.
$ python3.12 -m timeit 'f"Welcome to {2 ** 3}."'
5000000 loops, best of 5: 69.8 nsec per loop
$ python3.12 -m timeit '"Welcome to {}.".format(2 ** 3)'
2000000 loops, best of 5: 112 nsec per loop
$ python3.12 -m timeit '"Welcome to %d." % 2 ** 3'
5000000 loops, best of 5: 82.2 nsec per loop
$ python3.12 -m timeit '"Welcome to " + str(2 ** 3) + "."'
5000000 loops, best of 5: 77.5 nsec per loop
- elevatedastalt 3y agoSurprising that the double concatenation is the second fastest!
- L3viathan 3y agoProbably because the string is so short.
- Hamuko 3y agoYeah, it's not great with long strings. f-strings seem to be great just about always though. Highly recommend. $ python3.12 -m timeit -s 'import string' -s 'x = string.printable * 50' 'f"Welcome to {x}."' 2000000 loops, best of 5: 106 nsec per loop $ python3.12 -m timeit -s 'import string' -s 'x = string.printable * 50' '"Welcome to {}.".format(x)' 2000000 loops, best of 5: 200 nsec per loop $ python3.12 -m timeit -s 'import string' -s 'x = string.printable * 50' '"Welcome to %s." % x' 2000000 loops, best of 5: 169 nsec per loop $ python3.12 -m timeit -s 'import string' -s 'x = string.printable * 50' '"Welcome to " + str(x) + "."' 1000000 loops, best of 5: 214 nsec per loop $ python3.12 -m timeit -s 'import string' -s 'x = string.printable * 50' '"Welcome to " + x + "."' 1000000 loops, best of 5: 198 nsec per loop len(string.printable * 50) = 5000
- owl57 3y agoTIL. str.format and % parse the format string at runtime, so it's expected that they're slower. But I thought the f-string desugars to something similar to the last one. Turns out it's not, it compiles to specialized opcodes and avoids function calls: https://bugs.python.org/issue25483 https://bugs.python.org/issue25483 https://bugs.python.org/issue27078 https://bugs.python.org/issue27078
- DonHopkins 3y agoI used to be skeptical, but the great David Beazley convinced me that f-strings rocked because they were faster and better, in his talk "The Fun of Reinvention (Screencast)". The point he made was to embrace the new features of Python, and put old Python out of its misery, instead of wasting your time with backwards compatibility. Just call whatever you're doing in the latest version of Python a "prototype", then ship it. At 10:20 he talks about things you can do to put old Python out of its misery (dead parrot), including f-strings and ordered dictionaries. The Fun of Reinvention (Screencast): https://www.youtube.com/watch?v=js_0wjzuMfc https://www.youtube.com/watch?v=js_0wjzuMfc Invited Keynote Talk from PyCon Israel, June 12, 2017. I cause trouble and build a framework using all sorts of new Python 3.6+ features.