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.
- Tell
split()(any whitespace, no empty pieces) fromsplit(",")(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)
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.
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))
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.
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. Usesplit(). - Forgetting that punctuation stays on the words.
- Unpacking without checking the number of pieces.
- Calling
joinon numbers: every piece must already be text.
split()breaks on any whitespace and drops empty pieces;split(sep)cuts at everysepand 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.