What is the most efficient way to concatenate many Python strings together?


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 −

  • Concatenate using the + Operator when the strings are less
  • Concatenate using the Joins when the strings are less
  • Concatenate using the + Operator when the strings are many
  • Concatenate using the Joins when the strings are many

Let’s begin the examples

Concatenate Strings using the + Operator

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())

Output

Execution Time =  0.009820308012422174

Concatenate Strings using the Join

Example

Let us concatenate using the .join(). 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="''.join(['Amit' + 'Jacob' + 'Tim' +'Tom' + 'Mark'])") # Displaying the execution time print("Execution Time = ",s.timeit())

Output

Execution Time =  0.0876248900021892

As shown above, using the + operator is more efficient. It takes less time for execution.

Concatenate Many Strings using the + Operator

Example

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)

Output

0.0022547245025634766

Concatenate Many Strings using the Join

Example

We will now concatenate many strings using Join and check the execution time. When we have many strings, the join is a better and faster option −

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)

Output

0.000995635986328125

As shown above, using the join() method is more efficient when there are many strings. It takes less time for execution.

Updated on: 16-Sep-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements