Python split() Function: How It Works
In this article
Python's split() method breaks a string into a list of substrings. Called with no arguments, it splits on any run of whitespace and discards leading and trailing whitespace, so "a b\tc\n".split() returns ['a', 'b', 'c']. Called with a separator, it splits on that exact string: "a,b,c".split(",") returns ['a', 'b', 'c']. An optional second argument, maxsplit, limits how many splits are performed. That is the whole function in one line; the rest of this guide covers the details that trip people up.
What You'll Need
- A working Python 3 installation (any recent 3.x version is fine; the behaviour described here has been stable for years).
- A way to run Python: the interactive interpreter, IDLE, VS Code, PyCharm, or a terminal with
python3. - A string to experiment with. You can type one directly at the prompt; no file or package is required.
Note that split() is a string method, not a module function. You do not import anything. If you see code that calls split() on a list or a number, that is a bug, not a missing import.
Step-by-Step
- Open a Python prompt or a new script. In a terminal, run
python3(on Windows,pythonorpyusually works). You should see the>>>prompt. Any code below can be typed there or saved in a.pyfile and run. - Create a string variable. For example:
text = "red,green,blue". Strings in Python are immutable, sosplit()never changestext; it returns a new list. - Call
split()with no arguments to split on whitespace. Try"one two three".split(). The result is['one', 'two', 'three']. Consecutive spaces, tabs and newlines are treated as a single separator, and empty strings at the start or end are dropped. This is the behaviour most people want when parsing words from a line of text. - Pass a separator string to split on something specific. Try
"red,green,blue".split(","). The result is['red', 'green', 'blue']. The separator can be any string, including multi-character ones:"a--b--c".split("--")gives['a', 'b', 'c']. Unlike the no-argument form, an explicit separator keeps empty strings:"a,,b".split(",")returns['a', '', 'b']. - Use the
maxsplitargument to limit the number of splits."a,b,c,d".split(",", 2)returns['a', 'b', 'c,d']. Python performs at most two splits, and the remainder of the string stays together in the final element. This is handy for parsing lines where only the first field is a key and everything after it is the value. You can also passmaxsplitwith no separator by using a keyword:"a b c d".split(maxsplit=1)returns['a', 'b c d']. - Store or inspect the result. The return value is always a list of strings. Assign it:
parts = text.split(","), then checklen(parts)or index into it withparts[0]. If you only need the first field,text.split(",", 1)[0]avoids building a long list. - Handle the common follow-up: stripping whitespace around fields. Splitting
"a, b, c".split(",")gives['a', ' b', ' c']because the spaces are part of each field. Clean them with a list comprehension:[p.strip() for p in text.split(",")]. Do not expectsplit()to trim for you when you pass a separator. - Split from the right if needed. The related method
rsplit()works the same way but countsmaxsplitfrom the right."a.b.c".rsplit(".", 1)returns['a.b', 'c'], which is useful for file extensions. - Know the related methods.
splitlines()splits on line boundaries and is better thansplit("\n")for text that may use\r\n.partition()splits once and returns a three-tuple of before, separator and after, which is cleaner when you need to keep the separator.
Common Mistakes
- Passing an empty separator.
"abc".split("")raisesValueError: empty separator. If you want individual characters, uselist("abc"). - Expecting
split()to modify the original string. It returns a new list; the original is unchanged. Reassign if you want to keep the result:parts = text.split(","). - Confusing
split()withsplit(" "). The no-argument version collapses runs of whitespace and drops empty strings; the explicit-space version does not."a b".split()gives two items,"a b".split(" ")gives three, the middle one empty. - Forgetting that
maxsplitis positional.split(",", 2)means split at most twice, not split into two pieces. To get exactly two pieces, usesplit(",", 1)orpartition(","). - Calling
split()on a non-string. Numbers and lists have nosplitmethod. Convert first withstr(value), or split the string before converting fields withint()orfloat(). - Assuming a separator is a regular expression. It is a plain string. For pattern-based splitting, use
re.split()from theremodule.
Tips
- Use
split()with no arguments for free-form text such as sentences or log lines; it handles tabs and newlines for free. - Use
split(",")for CSV-style data only when fields cannot contain commas. For real CSV files with quoted fields, use thecsvmodule instead, becausesplit()will break quoted values apart. - Chain
strip()before or after splitting to avoid stray whitespace:line.strip().split(","). - Unpack the result when you know the field count:
name, age = "Ada,36".split(","). This raises a clear error if the count is wrong, which is often better than silently indexing. - Remember that
split()returns strings, so convert numbers explicitly:[int(x) for x in "1,2,3".split(",")].
Troubleshooting
You get one item in the list. The separator you passed does not appear in the string, or you used a character that looks similar but is not the same (for example a comma versus a full-width comma). Print the string with repr(text) to see hidden characters.
You get empty strings. With an explicit separator, consecutive separators produce empty fields, and a leading or trailing separator produces an empty field at that end. Filter them with [p for p in text.split(",") if p] if that is what you want.
You get a ValueError about too many values to unpack. The string contained more separators than you expected. Use maxsplit or partition(), or check len(parts) before unpacking.
You get AttributeError: 'list' object has no attribute 'split'. You are calling split() on something that is already a list. Either split the original string before turning it into a list, or iterate over the list and split each item.
The split looks correct but comparisons fail. Hidden whitespace or carriage returns are usually the cause. Apply .strip() to each field and check with repr().
If that did not work, reduce the problem to a one-line example in the interactive prompt. If the one-liner behaves as expected, the issue is in the surrounding data or code, not in split() itself.
Frequently Asked Questions
Does split() change the original string?
No. Strings are immutable in Python. split() returns a new list and leaves the original string untouched.
What is the difference between split() and split(" ")?
The no-argument form splits on any whitespace, collapses consecutive whitespace and drops empty strings. split(" ") splits only on single spaces and keeps empty fields, so it produces different results for text with double spaces, tabs or newlines.
Can I split on multiple different characters at once?
Not with split() alone. Use re.split(r"[,;]", text) from the re module, or replace the other characters with one separator first.
How do I split a string into exactly two parts?
Use split(separator, 1) or partition(separator). The latter always returns three elements: before, the separator itself, and after.
Why does split() return an empty list?
It does not for a normal string. An empty string "" with no arguments returns [], and "".split(",") returns ['']. If you see [] unexpectedly, the variable is probably empty.
Does split() work on bytes?
Yes, bytes objects have their own split(), but the separator must also be a bytes object, for example b"a,b".split(b","). Mixing str and bytes raises a TypeError.