liveBook · Manning

Split

As explained in The Quick Python Book, Fourth Edition

split is a string method that divides a string into a list of substrings according to a separator or, by default, whitespace.

Python’s string method split() divides a string into a list of substrings. With no argument, it splits on whitespace, including spaces, tabs, and newlines. Pass a separator to split on a particular sequence instead. The separator is not included in the returned substrings. section 6.4.1 section 8.13.2

Choose the boundary

"You\t can\n split this".split() returns ['You', 'can', 'split', 'this']. "Mississippi".split("ss") returns ['Mi', 'i', 'ippi']. For a delimited record, "Illinois|1979/01/01|17.48|994".split("|") returns four fields—all still strings. section 6.4.1 section 21.2.3

An optional second argument limits the number of splits. For example, 'a b c d'.split(' ', 1) returns ['a', 'b c d'], leaving the remaining text together. To set a limit while retaining whitespace splitting, supply None as the first argument. section 6.4.1

Common uses need different boundaries:

  • Count whitespace-separated words in each file line with len(line.split()). section 8.13.2
  • Split text on "\n\n" when blank lines separate paragraphs. section 21.2.2
  • Split a known delimited record, then convert fields that need non-string types. section 21.2.3

Splitting is not text normalization: punctuation and case can still make otherwise matching words differ. Also, splitting a whole file on "\n" removes the newline characters; summing the lengths of the resulting pieces will undercount characters. For character counts, process the original lines instead. section 21.2.2 section 8.13.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains default and explicit separators, limited splits, and omitted delimiters; stops short of implementation internals.
Examples
Uses mixed whitespace, substring splitting, pipe-delimited temperature data, blank-line paragraphs, and a file character-count error.
What it assumes
Assumes familiarity with Python strings, lists, and file lines while explaining split’s arguments through examples.
What you can do after
Apply it via Python strings to extract text fields and avoid losing separators needed for counts.
How it connects
Connects split to join, text normalization, word counting, and delimited files.

Also explained in

Compare how 11 books explain split →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.