Python split() and join(): Separate and Combine Text
Core idea
Use text.split(separator) to separate text at an explicit delimiter. It returns a list: an ordered collection, shown in square brackets here. Lists are taught later; for now, treat the returned list as a collection of string pieces. separator.join(pieces) combines those strings with the separator between them.
parts = "tea|rice|oil".split("|")print(parts)print(" / ".join(parts))Split removes the pipe separators and returns three strings. Join inserts the new separator between adjacent pieces, not before or after them.
Whitespace versus explicit separators
print(" tea rice ".split())print("tea,,rice,".split(","))With no separator, runs of whitespace are treated as a single delimiter and leading/trailing whitespace is ignored. With an explicit comma, adjacent or trailing delimiters produce empty pieces.
Intentional error: empty separator
An empty delimiter is invalid for split. Join accepts an empty separator and combines the pieces directly.
Common mistake
Call join on the separator, not on the list. All pieces must be strings. Splitting on commas is not a general CSV parser: quoted fields need a proper CSV parser, taught later.
Practice
Transform "a:b::c" into "a/b//c" by splitting and joining. Explain why the empty piece is retained.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Split and join
Check your understanding of split and join.
What is printed?
print("a||b".split("|"))What is printed?
print("-".join("red blue".split()))Which expression splits text on runs of whitespace?
Which statement correctly describes join?