At the time of asking this question, I\'m using Python 3.8
When I say efficient, I\'m only referring to the speed at which the strings are concatenated,
Why don't you try it out? You can use timeit.timeit() to run a statement many times and return the overall duration.
Here, we use s
to setup the variables a
and b
(not included in the overall time), and then run the various options 10 million times.
>>> from timeit import timeit
>>>
>>> n = 10 * 1000 * 1000
>>> s = "a = 'start'; b = ' end'"
>>>
>>> timeit("c = a + b", setup=s, number=n)
0.4452877212315798
>>>
>>> timeit("c = f'{a}{b}'", setup=s, number=n)
0.5252049304544926
>>>
>>> timeit("c = '%s%s'.format(a, b)", setup=s, number=n)
0.6849184390157461
>>>>
>>> timeit("c = ''.join((a, b))", setup=s, number=n)
0.8546998891979456
>>>
>>> timeit("c = '%s%s' % (a, b)", setup=s, number=n)
1.1699129864573479
>>>
>>> timeit("c = '{0}{1}'.format(a, b)", setup=s, number=n)
1.5954962372779846
This shows that unless your application's bottleneck is string concatenation, it's probably not worth being too concerned about...
If you're performing literally millions of operations, you'll see a speed improvement of about 1 second.
Note that your results may vary quite drastically depending on the lengths (and number) of the strings you're concatenating, and the hardware you're running on.