Is python += string concatenation bad practice?

Is python += string concatenation bad practice?

Is it bad practice?

Its reasonable to assume that it isnt bad practice for this example because:

  • The author doesnt give any reason. Maybe its just disliked by him/her.
  • Python documentation doesnt mention its bad practice (from what Ive seen).
  • foo += ooo is just as readable (according to me) and is approximately 100 times faster than foo = .join([foo, ooo]).

When should one be used over the other?

Concatenation of strings have the disadvantage of needing to create a new string and allocate new memory for every concatenation! This is time consuming, but isnt that big of a deal with few and small strings. When you know the number of strings to concatenate and dont need more than maybe 2-4 concatenations Id go for it.

When joining strings Python only has to allocate new memory for the final string, which is much more efficient, but could take longer to compute. Also, because strings are immutable its often more practical to use a list of strings to dynamically mutate, and only convert it to a string when needed.

Its often convenient to create strings with str.join() since it takes an iterable. For example:

letters = , .join(abcdefghij)

To conclude

In most cases it makes more sense to use str.join() but there are times when concatenation is just as viable. Using any form of string concatenation for huge or many strings would be bad practice just as using str.join() would be bad practice for short and few strings, in my own opinion.

I believe that the author was just trying to create a rule of thumb to easier identify when to use what without going in too much detail or make it complicated.

If the number of string is small and strings are known in advance, I would go :

foo = f{foo}ooo

Using f-strings. However, this is valid only since python 3.6.

Is python += string concatenation bad practice?

Leave a Reply

Your email address will not be published. Required fields are marked *