Splitting, partitioning, and joining strings
In Chapter 2, Simple Data Types, we looked at different processing methods for a string object. We can transform a string into a new string, create strings from non-string data, access a string to determine properties or locations within the string, and parse a string to decompose it.
In many cases, we need to extract elements of a string. The split()
method is used to locate repeating list-like structures within a string. The partition()
method is used to separate the head and tail of a string.
For example, given a string of the form "numerator=355,denominator=115"
we can use these two methods to locate the various names and values. Here's how we can decompose this complex string into pieces:
>>> text="numerator=355,denominator=115" >>> text.split(",") ['numerator=355', 'denominator=115'] >>> items= _ >>> items[0].partition("=") ('numerator...