Python split() Function: Syntax and Examples
In this article
The split() function in Python breaks a string into a list of substrings based on a separator you choose. If you omit the separator, it splits on any whitespace and removes empty strings from the result. The basic syntax is string.split(sep=None, maxsplit=-1), where sep is the delimiter and maxsplit limits how many splits are performed. This guide walks through the syntax, practical examples, and common pitfalls so you can use split() correctly in your own code.
What You'll Need
- Python 3 installed on your computer (any recent version works; split() has been stable for years).
- A way to run Python code: the interactive interpreter, a script file, or a Jupyter notebook.
- Basic familiarity with strings and lists in Python.
Step-by-Step
- Understand the syntax. The method is called on a string object:
my_string.split(sep=None, maxsplit=-1). Both arguments are optional.sepis the delimiter string;maxsplitis an integer that limits the number of splits. The method returns a new list of strings and does not modify the original string. - Split on whitespace (default behavior). Call
split()with no arguments:"hello world".split()returns['hello', 'world']. This treats any run of whitespace (spaces, tabs, newlines) as a single separator and discards leading/trailing whitespace. It also removes empty strings, so"a b".split()gives['a', 'b']. - Split on a specific character. Pass the delimiter as a string:
"apple,banana,cherry".split(',')returns['apple', 'banana', 'cherry']. The delimiter can be any string, including multi-character sequences like"--"or"::". - Limit the number of splits with maxsplit. Use the second argument to cap how many times the string is split:
"a,b,c,d".split(',', 2)returns['a', 'b', 'c,d']. The first two commas are used as separators, and the rest of the string stays intact in the final element. This is useful when you want to keep part of the string unsplit, such as splitting a line into a key and a value. - Handle multiple delimiters. split() only accepts one separator string. To split on several different characters, use
re.split()from theremodule:import re; re.split(r'[,;]', "a,b;c")returns['a', 'b', 'c']. Alternatively, replace unwanted delimiters with a single one before calling split(). - Split from the right with rsplit(). If you need to limit splits from the end of the string, use
rsplit(sep, maxsplit). For example,"a,b,c,d".rsplit(',', 2)returns['a,b', 'c', 'd']. This is handy for parsing file paths or URLs where the last segments matter most. - Split lines with splitlines(). To break a string into lines at line boundaries (\n, \r\n, etc.), use
splitlines()instead of split('\n'). It handles different newline conventions and does not keep the newline characters. - Assign the result to variables. You can unpack the list directly:
first, second = "one two".split(). This raises a ValueError if the number of elements does not match the number of variables, so use it only when you are sure of the count.
Common Mistakes
- Expecting split() to modify the original string. Strings are immutable; split() returns a new list. You must assign the result to a variable.
- Using split('') to split into characters. An empty separator raises a ValueError. Use
list(my_string)to get individual characters. - Assuming split() with a delimiter removes empty strings. "a,,b".split(',') returns ['a', '', 'b'] . If you need to drop empty strings, filter them: .
- Forgetting that maxsplit counts splits, not resulting elements.
split(',', 1)produces two elements. The number of elements is at most maxsplit + 1. - Using split() on non-string objects. split() is a string method. For bytes, use
bytes.split()with a bytes separator; for lists, use other techniques.
Tips
- Use
split()without arguments for tokenizing text where whitespace is the natural separator. - When parsing CSV-like data, consider the
csvmodule instead of split() to handle quoted fields correctly. - Combine split() with
strip()to clean up each piece:[part.strip() for part in line.split(',')]. - Remember that split() is fast and efficient; for simple cases, it is preferable to regular expressions.
- Use
partition()when you need exactly three parts (before, separator, after) and want to keep the separator.
Troubleshooting
If split() does not behave as expected, check these common issues:
- ValueError: empty separator. You passed an empty string as sep. Use a valid delimiter or call split() with no arguments.
- Unexpected empty strings in the result. Consecutive delimiters produce empty strings. Filter them out or use a different approach.
- AttributeError: 'list' object has no attribute 'split'. You are calling split() on a list, not a string. Convert the list to a string first or access the string element.
- Too many values to unpack. The number of elements from split() does not match your variables. Use maxsplit or unpack with a star expression.
- Split does not handle multiple delimiters. Use
re.split()or preprocess the string.
Frequently Asked Questions
What does split() do in Python?
It divides a string into a list of substrings based on a specified separator (or whitespace by default).
Can I split a string into characters?
Yes, use list(my_string) or a list comprehension. split('') raises an error.
How do I split a string only once?
Pass maxsplit=1: "a,b,c".split(',', 1) returns ['a', 'b,c'].
What is the difference between split() and rsplit()?
split() starts from the left, rsplit() from the right. With maxsplit, they limit splits from opposite ends.
Does split() remove whitespace?
Only when called without arguments; it strips leading/trailing whitespace and collapses runs of whitespace. With a delimiter, whitespace is preserved unless it is the delimiter.
How do I split on multiple delimiters?
Use re.split(r'[,;]', text) from the re module, or replace delimiters with a single one before splitting.