Python's split() method breaks a string into a list of smaller strings, using a separator you choose (or whitespace by default). For example, "a,b,c".split(",") returns ['a', 'b', 'c']. It is one of the most common ways to turn raw text — CSV lines, log entries, user input — into usable pieces you can loop over, index, or convert to numbers. You do not need to install anything beyond Python itself; any Python 3 interpreter (IDLE, VS Code, or the terminal) is enough to follow along.
What You'll Need
- Python 3 installed on your computer (check with
python --versionorpython3 --versionin a terminal). - A way to run Python code: the interactive REPL, a
.pyfile, or an editor like VS Code or IDLE. - Basic familiarity with strings and lists (helpful but not required).
Step-by-Step
- Open a Python session. In a terminal, type
python(orpython3on macOS/Linux) and press Enter. You should see the>>>prompt. Alternatively, create a file namedsplit_demo.pyand run it withpython split_demo.py. - Call
split()with no arguments. Type"hello world".split()and press Enter. The result is['hello', 'world']. With no argument,split()treats any run of whitespace (spaces, tabs, newlines) as a single separator and removes leading/trailing whitespace. - Pass an explicit separator. Use
"a,b,c".split(",")to get['a', 'b', 'c']. The separator can be any string, including multi-character ones like" -- ". Note that the separator itself is not included in the output. - Limit the number of splits with
maxsplit."one two three four".split(" ", 2)returns['one', 'two', 'three four']. The second argument caps how many splits happen; the remainder stays together in the last element. This is handy for parsing lines where only the first field matters. - Split multi-line text.
"line1\nline2\nline3".splitlines()returns['line1', 'line2', 'line3']. Usesplitlines()instead ofsplit("\n")when you want to handle different newline styles cleanly. - Convert results to other types. After splitting, you often need numbers:
[int(x) for x in "1,2,3".split(",")]gives[1, 2, 3]. Strip whitespace first withx.strip()if the input has spaces around the commas. - Assign the pieces to variables. If you know the exact count, unpack directly:
first, second = "a b".split(). If the count does not match, Python raises aValueError, so only do this when you are sure of the shape of the input. - Check the result. Print the list and its length:
parts = "a,b,c".split(","); print(parts, len(parts)). Confirm there are no empty strings or unexpected extra elements before you rely on it downstream.
Common Mistakes
- Assuming
split()andsplit(" ")are the same. They are not.split()collapses runs of whitespace and ignores leading/trailing whitespace;split(" ")splits on every single space and can produce empty strings. - Forgetting that the separator is removed.
"a,b".split(",")gives['a', 'b'], not['a', ',', 'b']. If you need the separator back, usere.split()with a capturing group instead. - Expecting
split()to modify the original string. Strings are immutable;split()returns a new list and leaves the original unchanged. - Passing an empty separator.
"abc".split("")raisesValueError: empty separator. To split into individual characters, uselist("abc"). - Using
split()on a non-string. It only works on strings. Convert numbers withstr(x)first, or you will get anAttributeError. - Ignoring trailing delimiters.
"a,b,".split(",")returns['a', 'b', '']— the empty string is real. Filter it with a list comprehension if it is unwanted.
Tips
- Use
rsplit()when you want to split from the right, such as separating a filename from its extension:"archive.tar.gz".rsplit(".", 1)gives['archive.tar', 'gz']. - Combine with
strip()to clean up user input:[part.strip() for part in raw.split(",")]. - For CSV data with quoted commas, do not use
split(",")— use the built-incsvmodule, which handles quoting correctly. - Remember that
split()returns a list, so you can chain list methods like.index(),.count(), or slice it with[:3]. - When splitting on multiple possible separators, reach for
re.split(r"[,;]", text)from theremodule.
Troubleshooting
- Got
ValueError: empty separator: You passed an empty string. Uselist(text)to get characters, or supply a real separator. - Got
AttributeError: 'int' object has no attribute 'split': You calledsplit()on a number. Convert it first withstr(value). - Unexpected empty strings in the result: Your separator appears consecutively or at the ends. Filter with
[p for p in parts if p]or clean the input first. - Split did not break where you expected: Check for hidden characters such as tabs (
\t) or non-breaking spaces. Printrepr(text)to see exactly what is there. - Too many pieces: Use the
maxsplitargument to cap the number of splits, orrsplit()to split from the other end. - Unpacking error (
ValueError: too many values to unpack): The list length does not match your variables. Printlen(parts)and adjust, or use indexing instead of unpacking.
Frequently Asked Questions
What does split() return?
It returns a new list of strings. The original string is unchanged.
What is the difference between split() and split(" ")?
split() treats any whitespace run as one separator and trims ends; split(" ") splits on each literal space and can leave empty strings.
Can I split on multiple characters?
Yes. Pass any string as the separator, e.g. "a--b".split("--"). For multiple different separators, use re.split().
How do I split only the first occurrence?
Use split(sep, 1) or partition(sep). partition returns a 3-tuple including the separator.
Does split() work on bytes?
Yes, but you must pass a bytes separator, e.g. b"a,b".split(b","). Mixing str and bytes raises a TypeError.
How do I split a string into characters?
Use list(text). Calling split("") raises an error.