Python split() Method: How to Split Strings
In this article
To split a string in Python, call .split() on it with an optional separator and an optional maximum number of splits: text.split() splits on any whitespace, while text.split(",") splits on commas. The method returns a list of substrings and does not change the original string. Everything below shows the exact syntax, the arguments, the edge cases that trip people up, and how to fix them.
What You'll Need
- Python 3 installed (any recent 3.x version works; the syntax is the same across versions).
- A way to run code: the interactive interpreter, IDLE, VS Code, PyCharm, or an online Python runner.
- A string to experiment with — for example
"red,green,blue"or" hello world ".
Step-by-Step
- Open a Python prompt or a new script. In a terminal, type
python(orpython3on macOS and Linux) and press Enter. You will see the>>>prompt. Alternatively, create a file such assplit_demo.pyand run it withpython split_demo.py. The interactive prompt is best for quick experiments because it prints the result of every expression immediately. - Create a string variable. Type
text = "red,green,blue"and press Enter. Assigning the string to a name lets you reuse it without retyping. Strings are immutable in Python, so every split operation returns a new list and leavestextunchanged. - Call
.split()with no arguments. Typetext.split(). Because there is no comma in the string, the whole string comes back as a single-element list:['red,green,blue']. With no arguments,split()splits on runs of whitespace (spaces, tabs, newlines) and discards leading and trailing whitespace. It does not split on punctuation. - Pass a separator. Type
text.split(","). The result is['red', 'green', 'blue']. The separator is a plain string, not a regular expression, sosplit(".")splits on literal dots. To split on a comma followed by a space, usetext.split(", "); the separator is matched exactly. - Limit the number of splits. The second argument is
maxsplit. Typetext.split(",", 1)and you get['red', 'green,blue']. Only the first comma is consumed; the remainder stays intact in the last element. This is the standard trick for parsingkey=valuepairs where the value itself may contain the separator:"name=Ada Lovelace".split("=", 1)gives['name', 'Ada Lovelace']. - Split from the right if needed.
rsplit()works likesplit()but counts from the end."a.b.c".rsplit(".", 1)returns['a.b', 'c'], which is useful for file extensions. With nomaxsplit,rsplit()behaves identically tosplit(). - Split on multiple lines. Use
splitlines()to break a string at line boundaries:"one\ntwo\nthree".splitlines()returns['one', 'two', 'three']. Unlikesplit("\n"), it handles\r\nand other line endings and does not leave a trailing empty string when the text ends with a newline. - Handle the results. The return value is always a list, so you can index it (
parts[0]), unpack it (first, second, third = text.split(",")), or loop over it. Unpacking raisesValueErrorif the number of pieces does not match the number of names, so only unpack when you are sure of the count. - Split and rejoin. To normalise spacing, combine the two methods:
" ".join(text.split())collapses any run of whitespace into single spaces. This is a common cleanup step before comparing or storing user input.
Common Mistakes
- Expecting
split()to accept a regular expression. It does not. For pattern-based splitting, importreand usere.split(r"[,;]", text). Remember thatre.splitkeeps capture groups in the output if your pattern contains parentheses. - Assuming empty strings are removed.
"a,,b".split(",")returns['a', '', 'b']. The empty element is real. Filter it with a list comprehension such as[p for p in parts if p]if you do not want blanks. - Forgetting that a trailing separator produces an empty string.
"a,b,".split(",")gives['a', 'b', '']. This matters when reading CSV-style lines; use thecsvmodule for real CSV files because it handles quoting correctly. - Using
split(""). An empty separator raisesValueError: empty separator. To break a string into characters, uselist(text)instead. - Confusing
split()withstrip().strip()removes characters from the ends and returns a string;split()returns a list. They are often used together but are not interchangeable. - Calling
spliton a non-string. Numbers and lists have nosplitmethod. Convert first withstr(value)if you genuinely need to split a number's digits or formatting.
Tips
- Prefer
split()with no arguments for whitespace-separated input — it handles multiple spaces and tabs in one call. - Use
maxsplit=1whenever you are parsing a key and a value, so separators inside the value are preserved. - Chain
strip()on each piece when the input may have stray spaces:[p.strip() for p in text.split(",")]. - For file paths, use
pathliboros.pathrather than splitting on slashes, because path rules differ by operating system. - Remember that
split()returns a list, which is mutable; if you need a tuple, wrap it withtuple(...).
Troubleshooting
If split() returns one element when you expected several, the separator you passed does not appear in the string. Print the string with repr(text) to reveal hidden characters such as tabs or non-breaking spaces. If you get ValueError: empty separator, you passed ""; choose a real separator or use list(). If unpacking fails with ValueError: not enough values to unpack or too many values to unpack, print the list and count the pieces before assigning names, or use maxsplit to force a known count. If the output contains unexpected empty strings, check for leading, trailing, or doubled separators. If split is not recognised, confirm the object is a string — for example, a number read from input needs str() or should be parsed with int(). Finally, if a regex-style split is needed, switch to re.split() and test the pattern on a short sample first.
Frequently Asked Questions
What does split() return?
A list of strings. The original string is unchanged because strings are immutable.
What is the difference between split() and split(" ")?
split() splits on any run of whitespace and drops leading and trailing whitespace. split(" ") splits on each single space and keeps empty strings where spaces repeat.
Can I split on more than one separator at once?
Not with split(). Use re.split() from the re module with a character class such as r"[,;]".
How do I split a string into a fixed number of parts?
Pass maxsplit as the second argument, for example text.split(",", 2). The result has at most three elements.
How do I remove empty strings after splitting?
Filter the list: [p for p in parts if p]. Alternatively, use filter(None, parts).
Does split() work on bytes?
Yes, but you must pass a bytes separator, such as b",", and the result is a list of bytes objects, not strings.