Partitioning strings

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 convention that the underscore variable is for unused or dummy values:

>>> origin, _, destination = "Seattle-Boston".partition('-')

This convention is supported by many Python-aware development tools which will suppress unused variable warnings for underscore.

..................Content has been hidden....................

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