What is the best way to concatenate strings in Python?

4

I know I can concatenate strings with += , + , join() and append() . All of them give me the same result when I concatenate two strings.

What is the best way to concatenate strings in Python? What is the difference between the ones mentioned? When to use each?

    
asked by anonymous 03.03.2017 / 04:14

1 answer

4

In Python the strings are immutable and for that reason, when we concatenate two of them using the "+" operator, a new object of type string is created and the original objects lose their references.

An efficient way to do this concatenation is by using lists () () that are changeable structures and then transforming that list of strings into a single string, concatenating them with the join () method of the object str ():

Inefficient way

a = ""
for i in range(1000):
   a += "X"
print a

In this way you create several objects in memory, thus reducing processing power only to concatenate the two objects

efficient way

a = []
for i in range(1000):
   a.append('X')
a = ''.join(a)

This way you can reuse the object already created in memory, optimizing its processing power.

Have an interesting link talking about strings in python in this link

    
03.03.2017 / 04:25