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' # This is bad, instead you should do:
foo = ''.join([foo, 'ooo'])
The author pointed out that ''.join()
is not always faster than +
, so he is not against using +
for string concatenation.
But why is foo += 'ooo'
bad practice whereas foobar=foo+bar
is considered good?
- is
foo += bar
good? - is
foo = foo + 'ooo'
good?
Before this code snippet, the author wrote:
One final thing to mention about strings is that using join() is not always best. In the instances where you are creating a new string from a pre-determined number of strings, using the addition operator is actually faster, but in cases like above or in cases where you are adding to an existing string, using join() should be your preferred method.
foo + bar
andfoo += bar
, but apparently there is forfoo += 'ooo'
.. – Rexford+
versus''.join()
. Here it's comparing two ways of using+
. – Unfrockstr.join()
is not always better,foobar = ''.join(foo, bar)
isn't really better thanfoobar = foo + bar
. If you look at the whole context of the statement it's clearer that it is ment as an exceptoin for the advise thatjoin()
is preferable to+=
in most cases. The given example could probably be improved. – Soilasoilagefoo = ''.join([foo, 'ooo'])
seems very overkill in this example. Not only is it less readable but also 100 times slower than the other examples, according to some tests with the timeit-module. – Makebelievefoo += 'ooo'
... It's important to point out that the author of the Hitchhiker's Guide refers to "good" and "bad" in terms of performance: it is much more efficient to accumulate the parts in a list, which is mutable, and then glue (‘join’) the parts together when the full string is needed – Dykes