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.