Python Splitting and Joining in Practice
Splitting breaks one string into a list of pieces. Joining builds one string back from a list of pieces.
Break a sentence at its spaces
split() with no mark breaks at spaces. Each word becomes one piece.
sentence = "ada wrote the first program"
print(sentence.split())Break a line at its commas
split(",") breaks at each comma. The numbers stay as text pieces.
line = "ada,88,bob,95"
print(line.split(","))Glue pieces with a dash
The dash before join() is the glue. The three pieces become one date.
parts = ["2026", "11", "08"]
print("-".join(parts))Split, then join with new glue
split() breaks the name into words. join() glues them back with underscores.
words = "ada lovelace".split()
print("_".join(words))Example
line = "ada lovelace, bob hooper, cy lee"
names = line.split(", ")
print(names)
print("Count:", len(names))
first_names = []
for name in names:
first_names.append(name.split()[0])
print(first_names)
print(" and ".join(first_names))Key points
- Split: one string broken into a list at each split mark
- Use split() to break a string at its spaces
- Use split(",") to break a string at each comma
- Join: a list of pieces glued into one string
- Use " ".join(parts) to glue pieces with a space between them
- Use ",".join(parts) to glue pieces with a comma between them
- The string before join() is the glue for the pieces in the list.
In this example, one line holds three full names. split(", ") breaks the line into three names. The loop splits each name again and keeps its first word. join() glues the three first names with " and " between them. The count of 3 proves no name was lost.
Note
split() drops the split marks, so the marks never appear in the pieces.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does "a,b,c".split(",") give back?