Python's text split function, str.split(), breaks a string into a list of substrings based on a delimiter you choose. The shortest working example is "a,b,c".split(","), which returns ['a', 'b', 'c']. If you omit the delimiter, Python splits on any run of whitespace and discards empty strings at the ends. This guide covers the syntax, practical examples, and the mistakes that trip people up.
What You'll Need
- Python 3 installed (any recent version;
split()has been stable for years). - A way to run Python: the interactive interpreter, a script file, or a notebook.
- A string you want to break apart, either typed in or read from a file or API response.
Step-by-Step
- Open a Python session. Run
python3in a terminal (orpythonon Windows) to get the>>>prompt, or create a file such assplit_demo.pyand run it withpython3 split_demo.py. - Create a string variable. For example:
text = "red,green,blue". Keep the quotes matched; a stray quote is the most common cause of aSyntaxError. - Call
split()with a delimiter. Typetext.split(","). The result is a list:['red', 'green', 'blue']. The delimiter itself is removed from the output. - Try splitting on whitespace. Call
text.split()with no argument. Python treats any sequence of spaces, tabs, and newlines as one separator, so"a b\tc".split()gives['a', 'b', 'c']. This is the right choice for splitting words in a sentence. - Limit the number of splits. Pass
maxsplitas the second argument:"a:b:c:d".split(":", 2)returns['a', 'b', 'c:d']. Everything after the second delimiter stays together in the last element. This is useful for parsing lines where only the first field matters. - Split from the right if needed. Use
rsplit()with the same arguments to count from the end:"a:b:c:d".rsplit(":", 1)gives['a:b:c', 'd']. Handy for file extensions or trailing comments. - Split on newlines for multi-line text. Use
text.splitlines()rather thansplit("\n"); it handles Windows\r\n, old Mac\r, and Unix\nline endings consistently and does not leave a trailing empty string. - Clean up the pieces. Splitting usually leaves stray spaces. Apply
.strip()to each element:[part.strip() for part in text.split(",")]. This removes leading and trailing whitespace from every item. - Handle empty fields. Consecutive delimiters produce empty strings:
"a,,b".split(",")returns['a', '', 'b']. If you want to drop them, filter with[p for p in parts if p]. If empty fields are meaningful (for example, a CSV column with no value), keep them. - Assign the result. Store the list in a variable:
parts = text.split(","). You can then index it (parts[0]), loop over it, or unpack it:first, second, third = parts. Unpacking raises aValueErrorif the list length does not match.
Common Mistakes
- Forgetting that
split()returns a list, not a string. Calling string methods like.replace()directly on the result fails; index or loop first. - Assuming
split()without arguments splits on a single space. It splits on any whitespace run and drops leading/trailing empties. Usesplit(" ")if you need to preserve empty fields between single spaces. - Using
split("\n")on files from mixed systems. It leaves\rat the end of each line, which breaks comparisons. Usesplitlines(). - Passing a multi-character delimiter by mistake.
split(", ")only splits where a comma is followed by exactly one space;"a, b".split(", ")gives['a', ' b']. Strip afterwards or use a regular expression. - Expecting
maxsplitto be the first argument. It is the second:split(delimiter, maxsplit). Swapping them raises aTypeError. - Splitting CSV data with
split(). Quoted fields containing commas will break. Use the built-incsvmodule instead.
Tips
- Chain
strip()in a list comprehension rather than looping separately; it is shorter and clearer. - Use
partition()when you need exactly one split and want the delimiter kept:"key=value".partition("=")returns('key', '=', 'value'). - For complex patterns (multiple delimiters, optional spaces), use
re.split()from theremodule. It is more powerful but slower for simple cases. - Check the length of the result before indexing to avoid
IndexErroron unexpected input. - When splitting user input, strip first, then split, then strip each piece; users often add spaces around delimiters.
Troubleshooting
- Result is a single-element list. The delimiter you passed does not appear in the string. Print the string with
repr()to reveal hidden characters such as tabs or non-breaking spaces. - Empty strings appear unexpectedly. Consecutive delimiters or leading/trailing delimiters create empty elements. Filter them or use
split()with no argument if whitespace is the separator. TypeError: must be str or None, not int. You passed a number as the delimiter. Delimiters must be strings; convert withstr()first.ValueError: too many values to unpack. The list has more elements than the variables you assigned. Usemaxsplitor index the list instead.- Split works but comparisons fail. Hidden whitespace or line endings remain. Apply
.strip()to each element and usesplitlines()for line-based text.
Frequently Asked Questions
What does split() do when called with no arguments?
It splits on any run of whitespace (spaces, tabs, newlines) and removes empty strings from the start and end of the result. This is the standard way to split a sentence into words.
Can I split on multiple different delimiters at once?
Not with str.split(). Use re.split() with a character class, for example re.split(r"[,;]", text), which splits on commas or semicolons.
How do I keep the delimiter in the output?
Use partition() for a single split, or re.split() with a capturing group. str.split() always removes the delimiter.
Why does split(",") leave spaces in my results?
The delimiter is only the comma; spaces are ordinary characters. Strip each element afterwards, or split on ", " if the format is consistent.
Does split() modify the original string?
No. Strings are immutable in Python; split() returns a new list and leaves the original unchanged.
What is the difference between split() and splitlines()?
splitlines() splits only on line boundaries and handles all common newline styles. split("\n") splits only on the Unix newline character and can leave carriage returns behind.