Splitting and Joining Strings
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Converting between a single formatted string and a list of tokens is a daily task in backend development. Python provides split() and join() for seamless conversions.
Splitting strings with split()
split() is a string method that cuts a string into a list of smaller strings. With no argument it cuts on any run of whitespace and drops the empty pieces.
By default, .split() breaks a string on any whitespace (spaces, tabs, newlines), discarding consecutive spaces.
sentence = "FastAPI PostgreSQL Docker"tags = sentence.split()print(tags)Example 1 · Counting the words in a review
review = "fast delivery and great support"words = review.split()print(words)print(len(words))['fast', 'delivery', 'and', 'great', 'support'] 5
What this code does
split()cuts the sentence on spaces and returns a list.lenof the list is the number of words.
The output is ['FastAPI', 'PostgreSQL', 'Docker'].
Custom delimiters: parsing CSV
Delimiter is the character or text that separates the parts of a string, such as a comma in a CSV line. Pass it to split(delimiter) to cut there.
Pass a specific delimiter to .split(delimiter) to parse structured data like CSV lines.
record = "101,Aarav,Software Engineer,Bengaluru"fields = record.split(",")print(fields[1])print(fields[3])Example 2 · Reading one CSV row
row = "A102,Laptop,2,45000"fields = row.split(",")total = int(fields[2]) * int(fields[3])print(fields[1])print(f"{fields[0]}: {total}")Laptop A102: 90000
What this code does
- Splitting on a comma gives four text fields.
- The quantity and price are text, so
intturns them into numbers before multiplying. - The f-string builds the final line.
Extracts 'Aarav' and 'Bengaluru' cleanly by splitting on commas.
Joining lists with join()
join() is a string method that glues the items of a list of strings into one string. It is called on the separator: ", ".join(items).
To combine an iterable of strings into one text, call .join() on the separator string: separator.join(list).
words = ["Python", "is", "awesome"]sentence = " ".join(words)print(sentence)Example 3 · Building a bulleted report
skills = ["FastAPI", "SQLAlchemy", "Pydantic", "pytest"]# Create a clean bulleted reportreport = "\n- ".join(skills)print("- " + report)- FastAPI - SQLAlchemy - Pydantic - pytest
What this code does
- Joins skills with newline and bullet dash
\n-. - Outputs each skill on a neat bulleted line.
The console displays Python is awesome. Using ", ".join(items) formats lists into clean comma-separated text.
Next step
Check your understanding
9 quick questions