Moment of zen: The way not be obvious at first – To concatenate, Invoke join on empty text. Something for nothing:
Figure 5.3: Moment of zen
This use of join()
is often confusing to the uninitiated, but with use, the approach taken by Python will be appreciated as natural and elegant.
Another very useful string method is partition()
which divides a string into three sections; the part before a separator, the separator itself, and the part after the separator:
>>> "unforgettable".partition('forget') ('un', 'forget', 'table')
The partition()
method returns a tuple, so this is commonly used in conjunction with tuple unpacking:
>>> departure, separator, arrival = "London:Edinburgh".partition(':') >>> departure London >>> arrival Edinburgh
Often, we're not interested in capturing the separator value, so you might see the underscore variable name used. This is not treated in a special way by the Python language, but there's an unwritten...