Книга: Practical Programming, Fourth Edition
Назад: Working with a List of Lists
Дальше: A Summary List

Splitting Strings

We introduced the method str.split in and promised to return to it later. The “later” is now.

The str.split method divides a string into parts

This method is a powerful, albeit imperfect, tool for text processing. It takes a string and splits it into fragments, essentially taking out whitespace characters. The fragments are returned as a new list and can be assigned to a variable. When the sep (“separator”) argument is not set to None, the separator is used instead of whitespace.

In the example in , str.split converts a string of color names into a list of strings:

 >>> colors = ​'red orange yellow green blue purple'​.split()
 >>> colors
 [​'red'​, ​'orange'​, ​'yellow'​, ​'green'​, ​'blue'​, ​'purple'​]

Another frequent application of the method is to split a line from a comma-separated values (CSV) file. As the name suggests, CSV file columns are separated by commas and can be extracted using str.split(',') (or similar methods):

 >>> colors = ​'red,orange,yellow,green,blue,purple'
 >>> colors.split() ​# Will not split
 [​'red,orange,yellow,green,blue,purple'​]
 >>> colors.split(​','​)
 [​'red'​, ​'orange'​, ​'yellow'​, ​'green'​, ​'blue'​, ​'purple'​]

Beware that if a column in a CSV file contains a comma (as in "Newman, Paul"), str.split(',') will split this column apart, as it is not aware of the structure of a CSV file. If you suspect that your CSV file has inner commas, use specialized modules (such as csv) to work with your data.

Назад: Working with a List of Lists
Дальше: A Summary List