Let's say I have two variables:
>>> a = "hello"
>>> b = "world"
I can concatenate them in two ways; using +
:
>>> a + b
"helloworld"
Or using an f-string:
>>> f"{a}{b}"
"helloworld"
Which way is better or a better practice? Someone told me the f-string is better practice in terms of performance and robustness, and I'd like to know why in detail.
There are two aspects to this: performance and convenience.
Using timeit
in Python 3.8.0, I get that concatenation using an f-string is consistently slower than +
, but the percentage difference is small for longer strings:
>>> from timeit import timeit
>>> timeit('a + b', setup='a, b = "hello", "world"')
0.059246900000289315
>>> timeit('f"{a}{b}"', setup='a, b = "hello", "world"')
0.06997206999949412
>>> timeit('a + b', setup='a, b = "hello"*100, "world"*100')
0.10218418099975679
>>> timeit('f"{a}{b}"', setup='a, b = "hello"*100, "world"*100')
0.1108272269993904
>>> timeit('a + b', setup='a, b = "hello"*10000, "world"*10000')
2.6094200410007033
>>> timeit('f"{a}{b}"', setup='a, b = "hello"*10000, "world"*10000')
2.7300010479993944
However, the f-string may be a bit more convenient when your inputs aren't already strings:
>>> a, b = [1, 2, 3], True
>>> str(a) + str(b)
'[1, 2, 3]True'
>>> f'{a}{b}'
'[1, 2, 3]True'