I am reading The Hitchhiker’s Guide to Python and there is a short code snippet
foo = \'foo\'
bar = \'bar\'
foobar = foo + bar # This is good
foo += \'ooo
It's reasonable to assume that it isn't bad practice for this example because:
foo += 'ooo'
is just as readable (according to me) and is approximately 100 times faster than foo = ''.join([foo, 'ooo'])
.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 isn't that big of a deal with few and small strings. When you know the number of strings to concatenate and don't need more than maybe 2-4 concatenations I'd 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 it's often more practical to use a list of strings to dynamically mutate, and only convert it to a string when needed.
It's often convenient to create strings with str.join() since it takes an iterable. For example:
letters = ", ".join("abcdefghij")
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.