runtime
52 / 250
lesson 52 String Algorithms · intermediate

Split text into words and fields

split() breaks text into a list: on any run of whitespace with no argument, or on an exact separator such as a comma. join() puts a list of texts back together.

You'll be able to
  • Tell split() (any whitespace, no empty pieces) from split(",") (exact separator, empty pieces kept)
  • Clean each piece after splitting, and check how many pieces there are before unpacking
  • Rebuild text with separator.join(pieces)
The idea

Text often holds several values: the words of a review, the fields of a line exported from a spreadsheet. split cuts it into a list of texts.

  • text.split(), with no argument, splits on any run of spaces, tabs or newlines, and ignores spaces at the ends. It never gives empty pieces.
  • text.split(",") splits at every comma exactly. Two commas in a row give an empty piece between them, and spaces stay attached to the pieces.

The reverse is join: " ".join(words) glues a list of texts together with a space between each pair.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Words and fields
review = "  Great   film,  slow start "
words = review.split()
print(words, len(words))
print(" ".join(words))
line = "C00164, Isaac ,New York,,consumer"
fields = line.split(",")
print(fields)
clean = []
for field in fields:
    clean.append(field.strip())
print(clean)
print("|".join(clean))
example-2.py · Unpacking the wrong number of pieces
entry = "HOM-22847:2:gift"
sku, quantity = entry.split(":")

Splitting is usually the first step of parsing: turning a line of text into typed values. Split, check the piece count, clean each piece, convert the numbers. Returning None for a bad line lets the caller skip it instead of crashing.

example-3.py · Parse a stock line
def parse_stock(line):
    """Return (sku, units, price) from "sku;units;price", or None if the line is malformed."""
    pieces = line.split(";")
    if len(pieces) != 3:
        return None
    sku = pieces[0].strip().upper()
    units = int(pieces[1])
    price = float(pieces[2])
    return sku, units, price

for line in ["hom-22847; 12 ;15.50", "ELE-24781;3;171.99", "SPO-11681;7", ""]:
    print(parse_stock(line))

When to use it: words from free text (split()), fields from a delimited line (split(sep)), and building text from a list (join). Mistakes to avoid:

  • Using split(" ") on text with double spaces: it produces empty pieces. Use split().
  • Forgetting that punctuation stays on the words.
  • Unpacking without checking the number of pieces.
  • Calling join on numbers: every piece must already be text.
Review
  • split() breaks on any whitespace and drops empty pieces; split(sep) cuts at every sep and keeps empty pieces.
  • Clean each piece, and check the piece count before unpacking.
  • sep.join(pieces) puts texts back together; " ".join(text.split()) normalises spaces.
  • Next: find where a piece occurs inside a text, and replace or extract around it.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Split text into words and fields — String Algorithms · Runtime