liveBook · Manning

Split

As explained in Python Workout: 50 ten-minute exercises

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

Python’s str.split divides a string into a list of substrings. Pass a separator such as ':' to split fields, or omit the argument to treat any run of spaces, tabs, and newlines as one delimiter. section 2.8 section 5.7

Use string splitting as part of larger transformations:

  • Split a sentence into words, transform each word, collect the results in a list, and recombine them with str.join. section 2.7 section 2.8
  • Split file lines into fields, but discard comments and blank lines before indexing the resulting list. section 5.7
  • Split whitespace-separated numbers, convert valid elements with int, filter with str.isdigit, and sum the results. section 7.7
  • Use regular expressions with re.split when more than one separator, such as commas and ::, is required. section 2.8

Translate a sentence word by word

sentence = 'this is a test translation' words = sentence.split() translated = [word[1:] + word[0] + 'ay' for word in words] print(' '.join(translated)) This produces: histay isway away estay ranslationtay. Splitting supplies individual words, while join prints the accumulated results on one line. section 2.7 section 2.8

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

Compare an explicit space separator with default whitespace handling: split(' ') preserves empty fields between repeated spaces, while split() treats runs of whitespace as one delimiter. section 2.8

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains separators, repeated whitespace, list results, immutable-string trade-offs, and the need for re.split with multiple delimiters.
Examples
Uses Pig Latin sentences, colon-separated password records, Apache logs, text files, and whitespace-separated integers.
What it assumes
Assumes familiarity with strings and lists while teaching separator choice, whitespace behavior, and sequence conversion.
What you can do after
Apply str.split with explicit or default delimiters, then combine, filter, convert, count, or transform the resulting substrings.
How it connects
Connects string splitting with strings as sequences, lists, str.join, list comprehensions, sets, files, 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: 50 ten-minute exercises. The section links point to the parts of the book it draws on.