String Splitting and Joining
Learn to split strings into lists, combine strings with join(), handle whitespace and empty fields, and process text safely.
In this lesson, you will learn
- ✓Explain how split() divides a string and returns a list of strings.
- ✓Distinguish splitting on arbitrary whitespace from splitting on an explicit separator.
- ✓Use join() to combine strings with a chosen separator.
- ✓Predict the behavior of split() and join() with empty strings, repeated separators, and non-string elements.
- ✓Trace examples, solve text-processing problems, and explain the exact output.
1. Understand split()
The split() method divides a string into smaller strings and returns those pieces in a list. By default, split() separates the string at runs of whitespace, such as spaces, tabs, and newline characters.
For example, 'learn Python today'.split() returns ['learn', 'Python', 'today']. The original string is not modified; split() creates a new list.
The default behavior is useful when you want to separate words without worrying about how many spaces appear between them.
Split a sentence into words
sentence stores the original text. split() separates the text at whitespace and returns a list containing three strings. The list is stored in words. len(words) returns 3 because the list contains three elements.
Note
2. Split using a specific separator
You can pass a separator to split() when the text uses a known delimiter, such as a comma, hyphen, or pipe character. Python separates the string at occurrences of that exact separator.
For example, 'red,green,blue'.split(',') returns ['red', 'green', 'blue']. The commas separate the values and are not included in the resulting list.
Unlike the default whitespace form, an explicit separator preserves empty fields between adjacent separators and at the ends of the string. This distinction matters when processing structured text.
Split comma-separated values
The comma is the separator. split(',') returns three list elements. List indexing starts at zero, so parts[1] is the second element, green.
Caution
3. Limit the number of splits
The optional maxsplit argument limits how many times split() separates the string. After that many splits, the remaining text stays together in the final element.
This is useful when only the first few fields matter, such as separating a command from the rest of its arguments.
Split only once
The separator is a colon. The maxsplit value 1 permits only one split. The first colon separates name from the remaining text. The second colon remains inside the second element.
Note
4. Understand join()
The join() method combines strings from an iterable into one string. The separator is the string on which you call join(), and the strings to combine are passed as its argument.
The syntax is separator.join(iterable). For example, '-'.join(['learn', 'by', 'doing']) returns 'learn-by-doing'. The hyphen is inserted between adjacent elements, not automatically at the beginning or end.
Every element supplied to join() must be a string. If the iterable contains an integer or another non-string value, join() raises TypeError. Convert values to strings first if that is the intended behavior.
Join words with a hyphen
The separator is the string '-'. join() places one hyphen between each pair of adjacent elements. The result is one string, not a list.
Note
5. Handle empty strings and non-string values
Empty strings are valid strings, so split() and join() can produce or process them. Their behavior depends on the separator and the input.
Joining an empty iterable returns an empty string. Joining a list containing an empty string also produces an empty string when the separator is empty. With a non-empty separator, empty elements can make separators appear at the beginning, end, or between adjacent separators.
If your data includes numbers, convert them to strings explicitly before joining. A list comprehension is one clear way to do this.
Join an empty list
The list contains no elements. There are no strings to combine and no separators to insert. The result is an empty string. repr() displays it as two quotation marks so that the empty value is visible.
Caution
6. Combine split() and join()
split() and join() are often used together when you need to normalize or rearrange text. For example, split() can separate words despite repeated whitespace, and join() can combine them using one consistent separator.
Be aware that this process can change the original formatting. Splitting and rejoining words with a single space removes extra whitespace between words and at the beginning or end.
Normalize whitespace
split() without an argument separates the words while treating runs of whitespace as delimiters. Leading and trailing whitespace do not create empty list elements. join() inserts exactly one space between the resulting words. The final string is 'learn Python well'.
Note
7. Step-by-step dry run
Trace the data after each statement. First identify whether the current value is a string, a list, or another type. Then determine exactly what split() returns or where join() inserts the separator.
Split and rebuild a sentence
The variable text contains one string with two commas. split(',') creates a list with three elements: red, green, and blue. The first print() displays the list representation. join() inserts the separator ' | ' between the three strings. The final print() displays the combined string.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Assuming split() and split(' ') behave identically.
Why it happens: split() without an argument treats runs of whitespace as one separator and ignores surrounding whitespace, while split(' ') splits on each literal space and can preserve empty fields.
Key takeaway: Use split() to separate on runs of whitespace. Use split(' ') only when you specifically want each space character to act as a separator, including the possibility of empty elements.
#2 Calling join() on the list instead of the separator.
Why it happens: join() is a string method, so the separator string calls join(iterable); the list itself does not provide the join() method.
Key takeaway: Use separator.join(parts), such as ', '.join(parts). The separator string determines what is inserted between elements.
#3 Passing integers directly to join().
Why it happens: join() requires strings in the iterable; convert numeric values to text explicitly before joining them.
Key takeaway: join() requires string elements. Convert numbers with str() or a suitable comprehension before joining.
#4 Assuming an explicit separator removes empty fields.
Why it happens: When an explicit separator is used, adjacent separators can represent empty fields, so split(',') may return empty strings for missing values.
Key takeaway: Consecutive or trailing separators can produce empty strings. Inspect the resulting list when processing structured text.
#5 Expecting join() to add the separator at the beginning and end.
Why it happens: join() inserts the separator only between elements, not at the beginning or end of the joined result.
Key takeaway: join() inserts the separator only between adjacent elements. It does not automatically add leading or trailing separators.
#6 Using split-and-join as a complete CSV parser.
Why it happens: Splitting on delimiters is not enough for full CSV parsing because quoted fields, escaped quotes, and embedded separators require a CSV-aware parser.
Key takeaway: Use the csv module when CSV records may contain quoted separators, escaped quotes, or embedded newlines.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What does split() do in Python?
Q2:What is the difference between split() and split(' ')?
Q3:How does join() work?
Q4:Why does join() raise TypeError for a list of integers?
Q5:How can you normalize whitespace in a string?
Q6:What happens when split() uses an explicit separator that appears consecutively?
Q7:What does maxsplit do?
Q8:Does join() add a separator at the beginning or end?
Q9:When should you use Python's csv module instead of split()?
Q10:Do split() and join() modify the original string?
Key takeaways
- split() divides a string and returns a list of strings.
- split() without an argument separates on runs of whitespace; split(' ') uses a literal space separator.
- An explicit separator can produce empty fields when separators are consecutive or appear at the end.
- maxsplit limits the number of splits and leaves the remaining text together.
- join() combines an iterable of strings using the separator string on which it is called.
- Every element passed to join() must be a string; convert non-string values when needed.
- An empty iterable joined with a separator produces an empty string.
- Combining ' '.join(text.split()) is useful for simple whitespace normalization.
- Use Python's csv module for CSV records that require quoting and escaping rules.
- Both methods return new values and do not modify the original string in place.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: