String concatenation

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 + ', ' ...

Get Practical Maya Programming with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.