liveBook · Manning

Split

As explained in Python Workout, Second Edition

str.split is the Python string method that divides a string into a list of substrings using a specified separator or, by default, runs of whitespace.

Use str.split to turn a string into a list of substrings. Pass a separator such as ':' to divide structured fields, or omit it to split on any run of spaces, tabs, and newlines. section 3.7 section 6.7

s = 'abc  def  ghi'     #1
s.split(' ')            #2
s.split()          #3

Compare explicit-space splitting with default whitespace splitting: repeated spaces produce empty fields with a separator, but disappear when split uses its default behavior. section 3.7

Keep these behaviors in mind when choosing a splitting strategy:

  • Every invocation returns a list of strings, whose length depends on the number of separators found. section 6.7
  • Use maxsplit when the input has a variable-length final field or when unpacking requires a bounded number of results. section 7.7
  • Use re.split when several different separators must be recognized; str.split accepts one separator string at a time. section 3.7
  • Filter or validate fields before conversion: str.isdigit rejects negative numbers, while try and except can handle int conversion failures. section 8.7

Parsing a calculator expression

Given '3 + 4', unpack the whitespace-separated result with `op, first_s, second_s = to_solve.split()`, convert the operands with int, and dispatch through a dictionary of operations. Use `split(maxsplit=3)` when the final field may contain spaces. section 7.7

Splitting usually begins a transformation pipeline: process the resulting words or fields, append generated values to a list, and use str.join when the final output must become one string. File processing can similarly split each line, update a set of unique words, or extract dictionary fields. section 3.7 section 6.11

How Python Workout, Second Edition covers it

How deep it goes
Explains separators, whitespace defaults, maxsplit, returned lists, and failure cases; stops short of implementing multiple separators without re.split.
Examples
Uses Pig Latin sentences, colon-delimited passwd records, calculator expressions, file word counts, and whitespace-separated integers.
What it assumes
Assumes familiarity with strings and basic lists while developing practical field extraction and defensive input handling.
What you can do after
Apply it via Python's str.split to tokenize text, unpack fields, cap splits, and feed results into later transformations.
How it connects
Connects string splitting with str.join, list unpacking, list comprehensions, sets, dictionaries, and regular expressions.

Also explained in

Compare how 11 books explain split →

Related concepts

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