What is the best way to concatenate strings in Python?

Asked

Viewed 17,403 times

7

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

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

1 answer

7


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

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

inefficient way

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

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

efficient way

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

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

Has an interesting link talking about operations with strings in python at this link

  • 3

    You have an interesting job here, with performance statistics: https://waymoot.org/home/python_string/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.