Joining strings

For joining large numbers of strings, avoid using the + or += operators. Instead, the  join() method should be preferred because it is substantially more efficient. This is because concatenation using the addition operator or it's augmented assignment version can lead to the generation of large numbers of temporaries, with consequent costs for memory allocation and copies. Let's see how join() is used.

The join() is a method on str which takes a collection of strings as an argument and produces a new string by inserting a separator between each of them. An interesting aspect of join() is how the separator is specified: it is the string on which join() is called.

As with many parts of Python, an example is the best explanation. To join a list of HTML color code strings into a semicolon separated string:

>>> colors = ';'.join(['#45ff23', '#2321fa', '#1298a3', '#a32312'])
>>> colors
'#45ff23;#2321fa;#1298a3;#a32312'

Here, we call join() on the separator we wish to use – the semicolon – and pass in the list of strings to be joined.

A widespread and fast Python idiom for concatenating together a collection of strings is to join() using an empty string as the separator:

>>> ''.join(['high', 'way', 'man'])
highwayman
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset