Home >Backend Development >Python Tutorial >How to concatenate multiple Python strings together efficiently?
The most efficient way to concatenate many Python Strings together depends on what task you want to fulfil. We will see two ways with four examples and compare the execution time −
Let’s start with the example
Let us concatenate using the operator. The timeit() is used to measure the execution time taken by the given code −
import timeit as t # Concatenating 5 strings s = t.Timer(stmt="'Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'") # Displaying the execution time print("Execution Time = ",s.timeit())
Execution Time = 0.009820308012422174
Let us use the .join() method to join. The timeit() function is used to measure the execution time of a given code.
import timeit as t # Concatenating 5 strings s = t.Timer(stmt="''.join(['Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'])") # Displaying the execution time print("Execution Time = ",s.timeit())
Execution Time = 0.0876248900021892
As shown above, using the operator is more efficient. It takes less time for execution.
We will now concatenate many strings and check the execution time using the time module −
from time import time myStr ='' a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash' l=[] # Using the + operator t=time() for i in range(1000): myStr = myStr+a+repr(i) print(time()-t)
0.0022547245025634766
We will now use Join to concatenate many strings and check the execution time. Concatenation is better and faster option when we have many strings −
from time import time myStr ='' a='gjhbxjshbxlasijxkashxvxkahsgxvashxvasxhbasxjhbsxjsabxkjasjbxajshxbsajhxbsajxhbasjxhbsaxjash' l=[] # Using the + operator t=time() for i in range(1000): l.append(a + repr(i)) z = ''.join(l) print(time()-t)
0.000995635986328125
As shown above, when there are many strings, it is more efficient to use the join() method. It takes less time to execute.
The above is the detailed content of How to concatenate multiple Python strings together efficiently?. For more information, please follow other related articles on the PHP Chinese website!