To split in Python, call text.split(sep) on a string: it returns a list of the pieces between each occurrence of sep. Call text.split() with no argument to split on whitespace instead.
'1,2,3'.split(',') # ['1', '2', '3']
'1 2 3'.split() # ['1', '2', '3']
Everything below follows the behavior documented for str.split() in the Python standard library docs. Output shown after # is example output.
How str.split() works
The signature is str.split(sep=None, maxsplit=-1). Both arguments are optional. The method never changes the original string, because strings are immutable. It builds and returns a new list.
sepis the delimiter string. It can be more than one character and is treated as a single delimiter.maxsplitis the maximum number of splits. The list then has at mostmaxsplit + 1elements. The default of-1means no limit.
'1,2,3'.split(',') # ['1', '2', '3']
'1,2,3'.split(',', maxsplit=1) # ['1', '2,3']
'1<>2<>3<4'.split('<>') # ['1', '2', '3<4']
The last line shows a multi-character separator. Only the exact two-character sequence <> cuts the string, so the lone < stays inside the last piece.
Split on whitespace: split() with no argument
When sep is not given or is None, Python uses a different algorithm. Runs of consecutive whitespace count as one separator, and the result has no empty strings at the start or end, even when the string has leading or trailing whitespace.
'1 2 3'.split() # ['1', '2', '3']
' 1 2 3 '.split() # ['1', '2', '3']
'1 2 3'.split(maxsplit=1) # ['1', '2 3']
This is the form to use for splitting a sentence into words, or for breaking up output where columns are separated by a variable number of spaces. Whitespace here means spaces, tabs and newlines, and other characters that str.isspace() accepts.
Compare that with split(' '), which passes a single space as an explicit separator. Two spaces in a row then produce an empty string between them:
'a b'.split(' ') # ['a', '', 'b']
'a b'.split() # ['a', 'b']
Why split(',') returns empty strings
With an explicit separator, consecutive delimiters are not grouped together. Each pair of neighbouring delimiters delimits an empty string, and a delimiter at the very start or end does the same:
'1,,2'.split(',') # ['1', '', '2']
'1,2,,3,'.split(',') # ['1', '2', '', '3', '']
Splitting an empty string behaves differently depending on the form. With a separator it returns a list holding one empty string. With no separator it returns an empty list:
''.split(',') # ['']
''.split() # []
' '.split() # []
This difference catches people out when they loop over the result. ''.split(',') gives you one iteration with an empty string, while ''.split() gives you none. If empty pieces are unwanted, filter them out: [part for part in text.split(',') if part]. See Python list comprehension if that syntax is new to you.
Split only the first or last separator: maxsplit and rsplit
A common job is to cut a line at the first = or : and keep the rest intact, because the value itself may contain the separator. Pass maxsplit=1:
'query=a=b'.split('=', 1)
# ['query', 'a=b']
str.rsplit() takes the same arguments but counts splits from the right. Apart from that, it behaves like split(). The difference only shows up when you give maxsplit:
'1,2,3'.split(',', 1) # ['1', '2,3']
'1,2,3'.rsplit(',', 1) # ['1,2', '3']
'archive.tar.gz'.rsplit('.', 1)
# ['archive.tar', 'gz']
The last line is the usual way to peel a file extension or a trailing number off a name that may contain the separator elsewhere.
Use the result: unpacking and converting
If you know how many pieces to expect, unpack the list directly into names:
user, domain = '[email protected]'.split('@')
print(user) # alex
print(domain) # example.com
This fails when the count is wrong. A string without @ returns a one-element list, and unpacking raises ValueError: not enough values to unpack (expected 2, got 1). Either check the input first, or use partition(), covered below, which always returns three parts.
Split returns strings, even when they look like numbers. Convert them yourself:
numbers = [int(part) for part in '10 20 30'.split()]
print(numbers) # [10, 20, 30]
print(sum(numbers)) # 60
To go the other way and join the pieces back into one string, use separator.join(list), for example '-'.join(['a', 'b']) returns 'a-b'. For the number of pieces, see counting items in a list and a string.
Split a string into lines: splitlines()
For multi-line text, use splitlines() rather than split('\n'). It splits on all the usual line boundaries, not only \n: carriage return \r, the Windows pair \r\n, vertical tab, form feed, and a few Unicode separators. That matters for text that came from another operating system.
'ab c\n\nde fg\rkl\r\n'.splitlines()
# ['ab c', '', 'de fg', 'kl']
'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
# ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
Line breaks are dropped unless you pass keepends=True. Unlike split('\n'), splitlines() returns an empty list for an empty string and does not add an extra empty item for a trailing line break:
'Two lines\n'.splitlines() # ['Two lines']
'Two lines\n'.split('\n') # ['Two lines', '']
''.splitlines() # []
Split once into three parts: partition()
str.partition(sep) splits at the first occurrence of sep and returns a tuple of three items: the part before, the separator itself, and the part after. If the separator is missing, you get the whole string followed by two empty strings. So the result always has three items, and unpacking never fails on the count:
'Monty Python'.partition(' ') # ('Monty', ' ', 'Python')
'Monty Python'.partition('-') # ('Monty Python', '', '')
rpartition() does the same from the right-hand end of the string.
Split on several delimiters: re.split()
str.split() takes a single separator string. The Python docs say that to split with multiple delimiters, you use re.split(). It takes a regular expression, so one pattern can match many separators:
import re
re.split(r'\W+', 'Words, words, words.')
# ['Words', 'words', 'words', '']
re.split(r'[;,]\s*', 'a; b,c')
# ['a', 'b', 'c']
The first call, taken from the Python docs, shows that re.split() keeps the empty string after the final period, just like str.split() does with an explicit separator. The second splits on a semicolon or comma plus any spaces after it.
If the pattern contains capturing parentheses, the text of the matched separators is returned in the list too:
re.split(r'(\W+)', 'Words, words, words.')
# ['Words', ', ', 'words', ', ', 'words', '.', '']
Use maxsplit as a keyword argument. Since Python 3.13, passing maxsplit and flags positionally is deprecated, so write re.split(pattern, text, maxsplit=1).
Which method to use
| Goal | Use |
|---|---|
| Words separated by any amount of whitespace | text.split() |
| Fixed delimiter such as a comma | text.split(',') |
| Cut at the first or last delimiter only | split(sep, 1) or rsplit(sep, 1) |
| Always exactly three parts | text.partition(sep) |
| Lines of text | text.splitlines() |
| More than one delimiter or a pattern | re.split(pattern, text) |
If the result is not what you expected
Print the list with print(repr(text.split(','))) or look at the pieces one by one. Stray spaces after commas leave leading spaces on items: 'a, b'.split(',') gives ['a', ' b']. Either split on ', ' or strip each piece with part.strip(). For text with quoted fields, such as CSV where values may contain commas, a plain split cuts inside the quotes, so use a real parser instead. The same advice applies to formatting the result afterwards, which Python f-strings covers.
Frequently asked questions
- What does split() return in Python?
- str.split() always returns a list of strings. With no arguments it splits on runs of whitespace. With a separator, such as split(','), it cuts the string at every occurrence of that separator and returns the pieces between them.
- How do I split a string into a list of characters?
- Use list(text). The split() method cannot do this, because it needs a non-empty separator to cut at. For example, list('abc') returns ['a', 'b', 'c'].
- How do I split on more than one delimiter?
- str.split() takes one separator string, so use re.split() with a regular expression instead. The pattern r'[;,]' splits on either a semicolon or a comma. The Python docs point to re.split() for exactly this case.
- Why does split(',') give empty strings?
- When you pass a separator, consecutive separators and separators at the start or end each produce an empty string. For example, '1,2,,3,'.split(',') returns ['1', '2', '', '3', '']. Split with no argument to skip empty strings from extra whitespace.