Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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', '=', '355')
>>> items[1].partition("=")
('denominator', '=...