In a few places in this book, we built short strings into longer strings. This process is called string concatenation. We often did this through the str.join
method:
>>> planets = 'Venus', 'Earth', 'Mars' >>> ', '.join(planets) 'Venus, Earth, Mars'
We also used string formatting:
>>> '%s, %s, %s' % planets 'Venus, Earth, Mars'
Why didn't we use string addition, such as:
>>> planets[0] + ', ' + planets[1] + ', ' + planets[2] 'Venus, Earth, Mars'
When adding more than two strings, Python ends up creating temporary strings. When the strings are large, this can cause unnecessary memory pressure. Consider all the work Python has to do when adding more than two strings:
>>> a = planets[0] + ', ' >>> b = a + planets[1] >>> c = b + ', ' >>> d = c + planets[2] >>> d 'Venus, Earth, Mars'
Of the four strings created to get our result, three of them were immediately unnecessary!
String addition should be avoided when concatenating more than two strings. As a bonus, using addition requires the most code and it is extremely unreadable.