Skip to content
PythonStrings and Textbeginner18 min read

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

Split a sentence into words
python
sentence = 'Learn Python today'
words = sentence.split()
print(words)
print(len(words))
Output
['Learn', 'Python', 'today'] 3

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

Calling split() without an argument is different from calling split(' '). The default form handles runs of whitespace and ignores leading and trailing whitespace when creating the words.

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

Split comma-separated values
python
colors = 'red,green,blue'
parts = colors.split(',')
print(parts)
print(parts[1])
Output
['red', 'green', 'blue'] green

The comma is the separator. split(',') returns three list elements. List indexing starts at zero, so parts[1] is the second element, green.

Caution

An explicit separator must not be an empty string. Calling text.split('') raises ValueError. If you need to split on arbitrary whitespace, use split() without an argument.

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

Split only once
python
text = 'name:age:city'
print(text.split(':', 1))
Output
['name', 'age:city']

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

With maxsplit=0, split() without an explicit separator returns the string without removing leading whitespace through splitting; it does not perform ordinary word separation. Use a positive maxsplit when you want a limited number of splits.

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

Join words with a hyphen
python
parts = ['learn', 'by', 'doing']
result = '-'.join(parts)
print(result)
Output
learn-by-doing

The separator is the string '-'. join() places one hyphen between each pair of adjacent elements. The result is one string, not a list.

Note

The separator owns join(). Write ', '.join(parts), not parts.join(', '). Strings do not have a join() method that operates on a list supplied to the list itself.

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

Join an empty list
python
parts = []
print(repr(','.join(parts)))
Output
''

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

Calling ', '.join([10, 20, 30]) raises TypeError because the elements are integers. Use ', '.join(str(number) for number in numbers) when converting those values to text is appropriate.

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

Normalize whitespace
python
text = ' learn Python\twell '
words = text.split()
cleaned = ' '.join(words)
print(cleaned)
Output
learn Python well

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

The split-and-join whitespace technique is useful for simple text normalization, but it is not a complete parser for quoted CSV fields. Use Python's csv module for real CSV data that may contain quoted commas, embedded newlines, or escaped quotes.

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

Split and rebuild a sentence
python
text = 'red,green,blue'
parts = text.split(',')
print(parts)
result = ' | '.join(parts)
print(result)
Output
['red', 'green', 'blue'] red | green | blue

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

split() changes the data's structure from one string to a list. join() combines string elements into one string. Neither method modifies the original string in place.

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.

Incorrect Approach
script.py
python
Assuming split() and split(' ') behave identically.
Correct Solution
script.py
python
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.

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.

Incorrect Approach
script.py
python
Calling join() on the list instead of the separator.
Correct Solution
script.py
python
Use separator.join(parts), such as ', '.join(parts). The separator string determines what is inserted between elements.

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.

Incorrect Approach
script.py
python
Passing integers directly to join().
Correct Solution
script.py
python
join() requires string elements. Convert numbers with str() or a suitable comprehension before joining.

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.

Incorrect Approach
script.py
python
Assuming an explicit separator removes empty fields.
Correct Solution
script.py
python
Consecutive or trailing separators can produce empty strings. Inspect the resulting list when processing structured text.

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.

Incorrect Approach
script.py
python
Expecting join() to add the separator at the beginning and end.
Correct Solution
script.py
python
join() inserts the separator only between adjacent elements. It does not automatically add leading or trailing separators.

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.

Incorrect Approach
script.py
python
Using split-and-join as a complete CSV parser.
Correct Solution
script.py
python
Use the csv module when CSV records may contain quoted separators, escaped quotes, or embedded newlines.

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.

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?
Answer:
split() divides a string into a list of strings. Without an argument, it separates on runs of whitespace and ignores leading and trailing whitespace when forming tokens. With an explicit separator, it splits at that separator and can preserve empty fields. For example, 'red,green'.split(',') returns ['red', 'green'].
Q2:What is the difference between split() and split(' ')?
Answer:
split() treats runs of whitespace, including spaces and tabs, as separators and does not create empty tokens from leading or trailing whitespace. split(' ') uses a literal space as the separator, so consecutive spaces can create empty strings. For example, 'red green'.split() returns ['red', 'green'], whereas 'red green'.split(' ') returns ['red', '', 'green'].
Q3:How does join() work?
Answer:
join() combines an iterable of strings into one string, inserting the separator between adjacent elements. For example, '-'.join(['a', 'b', 'c']) returns 'a-b-c'. The method is called on the separator string.
Q4:Why does join() raise TypeError for a list of integers?
Answer:
join() expects the iterable's elements to be strings. Integers are not converted automatically. Convert them explicitly, for example ', '.join(str(number) for number in [10, 20, 30]), which returns '10, 20, 30'.
Q5:How can you normalize whitespace in a string?
Answer:
For simple whitespace normalization, use ' '.join(text.split()). The default split() separates words across runs of whitespace and removes leading and trailing whitespace from the tokenization process. join() then inserts exactly one space between the words.
Q6:What happens when split() uses an explicit separator that appears consecutively?
Answer:
Each occurrence of the explicit separator is treated as a boundary, so consecutive separators can create empty strings. For example, 'A,,C'.split(',') returns ['A', '', 'C']. This matters when parsing records with empty fields.
Q7:What does maxsplit do?
Answer:
maxsplit limits how many splits are performed. For example, 'a:b:c'.split(':', 1) returns ['a', 'b:c']; only the first colon is used as a split point.
Q8:Does join() add a separator at the beginning or end?
Answer:
No. join() inserts the separator only between adjacent elements. For example, '-'.join(['a', 'b']) returns 'a-b', not '-a-b-'. Empty elements can affect the visible result, but the separator is still inserted only between elements.
Q9:When should you use Python's csv module instead of split()?
Answer:
Use the csv module for actual CSV data that can contain quoted commas, escaped quotes, or embedded newlines. A simple split(',') does not understand CSV quoting rules and may divide a field incorrectly.
Q10:Do split() and join() modify the original string?
Answer:
No. Strings are immutable. split() returns a new list, and join() returns a new string. The original string remains unchanged unless you explicitly assign a new value to a variable.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: