CodeBlanks Logo Icon CodeBlanks

split and join

Learn to split with split and join with join.

split and join

split splits a string by a separator into a list. join does the opposite: it joins a list with a separator into a string:

parts = "a,b,c".split(",")
# ["a", "b", "c"]
joined = ",".join(parts)
# "a,b,c"

If no separator is given, split uses whitespace. join requires all list items to be strings; otherwise it raises TypeError.

These two methods are very handy for working with CSV files and log lines.

split separator usage

The split separator can be any character. Splitting by space is common:

words = "hello world python".split()
# ["hello", "world", "python"]

If no separator is given, split() treats multiple spaces as one and trims leading/trailing spaces. This is ideal for parsing user input.

You can split more precisely by giving a separator.

Practice split and join together

Assign "a,b,c" to text. Assign text.split(",") to parts. Assign "-".join(parts) to result. Then print print(result).

Starter code

main.py
# Use split and join

Sample solution

main.py
text = "a,b,c"
parts = text.split(",")
result = "-".join(parts)
print(result)

Expected output

a-b-c

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does "a-b-c".split("-") return?

  • "abc"
  • ["a", "b", "c"] Correct answer
  • ["a-b-c"]
  • "a b c"

Explanation: split breaks by dash into a list.

2 Complete the join call

Question
result = ____.join(["a", "b", "c"])
Answer
result = ",".join(["a", "b", "c"])

Explanation: ",".join(...) joins the list with commas.

3 Match split and join

Term Meaning
split Split
join Join
",".join Join with comma
"-".split Split by dash

All lessons in Beginner