Python split(): How It Works and the Traps It Hides

split() breaks a string into a list of substrings. It’s one of the most used methods in Python, and one of the most misunderstood — because calling it with no argument and calling it with a space do different things.

"a b".split() # ['a', 'b'] "a b".split(" ") # ['a', '', 'b'] ← an empty string appeared

This guide covers what split() actually returns in each case, the maxsplit parameter, the three related methods people reach for too late, and when a regular expression is the right answer instead.

The short version
ReturnsAlways a list of strings — never a number
With no argumentSplits on any whitespace, collapsing runs
With a separatorSplits on every occurrence, keeping empties
Doesn’t accept regexThe argument is literal — use re.split()
Never use it on CSVQuoted commas break it — use the csv module

The syntax

string.split(sep=None, maxsplit=-1)

Both parameters are optional.

sep is the separator. When omitted, Python splits on whitespace with special rules — covered below. When given, it’s treated as a literal string, not a pattern.

maxsplit limits how many splits are performed. The default -1 means no limit.

And it always returns a list of strings:

text = "Python is an open source programming language"print(text.split()) # ['Python', 'is', 'an', 'open', 'source', 'programming', 'language']print(type(text.split())) # <class 'list'>

⚠️ If the separator isn’t found, you get a list with the original string in it — not an error, not an empty list:

text.split(',') # ['Python is an open source programming language'] ← one item

⚠️ The trap: split() and split(" ") are not the same

Comparison of split with no argument and split with an explicit space in Python, showing that the first collapses whitespace and trims edges while the second produces empty strings

This is where most bugs with split() come from.

"a b".split() # ['a', 'b'] "a b".split(" ") # ['a', '', 'b']" a b ".split() # ['a', 'b'] " a b ".split(" ") # ['', '', 'a', 'b', '', '']

With no argument, split() does three special things:

It splits on any whitespace — spaces, tabs and newlines alike.
It collapses runs, so two spaces act as one separator.
And it discards leading and trailing whitespace, producing no empty strings at the edges.

With an explicit separator, none of that happens. Every occurrence produces a split, including consecutive ones and ones at the edges.

"a\tb\nc".split() # ['a', 'b', 'c'] ← tab and newline count too"a,,b".split(",") # ['a', '', 'b'] ← the empty is deliberate ",a,b,".split(",") # ['', 'a', 'b', '']

⚠️ Those empty strings aren’t a bug — they mean “there was nothing between these two separators”, which in a data file is the difference between a blank field and no field.

When you want them gone, filter:

parts = [p for p in ",a,b,".split(",") if p] # ['a', 'b']

What an empty string gives you

Another case where the two forms differ:

"".split() # [] ← empty list "".split(",") # [''] ← list with one empty string

len() of the first is 0; of the second, 1. If your code checks if parts: to decide whether there was data, the second form is always truthy.


maxsplit: stopping early

It limits the number of splits — not the number of items returned.

text = "Python is an open source programming language"text.split(maxsplit=2) # ['Python', 'is', 'an open source programming language']

Two splits, three items. The remainder stays intact in the last position.

The most useful case is parsing key=value where the value may contain the separator:

"password=abc=123".split("=", 1) # ['password', 'abc=123'] ← the value keeps its equals sign

⚠️ Without maxsplit=1, you’d get three items and lose the structure.

rsplit(): from the right

Same method, splitting from the end. It only differs when maxsplit is used:

text.split(maxsplit=2) # ['Python', 'is', 'an open source programming language']text.rsplit(maxsplit=2) # ['Python is an open source', 'programming', 'language']

Useful for file extensions and paths, where the interesting part is at the end:

"archive.tar.gz".rsplit(".", 1) # ['archive.tar', 'gz']

The three methods people reach for too late

splitlines() for text with line breaks

It handles the three newline conventions, which split("\n") doesn’t:

text = "a\nb\r\nc"text.splitlines() # ['a', 'b', 'c'] text.split("\n") # ['a', 'b\r', 'c'] ← stray carriage return

⚠️ That \r is the Windows line ending, and it survives split("\n") attached to the previous item. It’s a classic source of comparisons that fail for no visible reason — "b\r" == "b" is False.

Any time you’re reading text that might come from another operating system, use splitlines().

partition() when you expect exactly one separator

It returns three items — before, the separator itself, and after — and never fails:

"user@mail.com".partition("@") # ('user', '@', 'mail.com')"noseparator".partition("@") # ('noseparator', '', '') ← no error, empty parts

The advantage over split() is unpacking safely:

user, sep, domain = "user@mail.com".partition("@") # always worksuser, domain = "nosign".split("@") # ValueError: not enough values to unpack

And rpartition() splits on the last occurrence instead of the first.

When split() isn’t enough

It doesn’t accept regular expressions

The argument is always a literal string:

"a1b2c".split(r"[0-9]") # ['a1b2c'] ← looked for the literal text "[0-9]"

For patterns, use re.split():

import rere.split(r"[;,]\s*", "a, b; c") # ['a', 'b', 'c'] ← comma or semicolon, with optional space

⚠️ One behaviour worth knowing: if the pattern has a capture group, the matched separators are included in the result.

re.split(r"(\d)", "a1b2c") # ['a', '1', 'b', '2', 'c'] ← the digits came along

Use a non-capturing group (?:...) if you don’t want that.

It can’t parse CSV

This is the one that costs real time.

line = 'a,"b,c",d'line.split(",") # ['a', '"b', 'c"', 'd'] ← wrong: four items, quotes broken

The quoted field contains a comma, and split() has no idea what a quote means.

import csv, ionext(csv.reader(io.StringIO(line))) # ['a', 'b,c', 'd'] ← correct: three fields

⚠️ A CSV parser also handles escaped quotes, embedded newlines and different dialects. Splitting on commas works until the first file with a quoted field — which, in real data, arrives quickly.

An empty separator raises

"abc".split("") # ValueError: empty separator

To get a list of characters, use list(): list("abc") gives ['a', 'b', 'c'].

Five string splitting methods in Python — split, split with maxsplit, rsplit, splitlines and partition — plus re.split and the csv module for cases split cannot handle

Two things that are simply not true

Both appear in a lot of material online, and both are wrong.

“If the delimiter appears twice, the rest is ignored.” It isn’t. split() divides at every occurrence — "a,,b".split(",") returns three items, including the empty one between the commas.

“It may not work with Unicode characters.” It works normally. "café açúcar".split() returns ['café', 'açúcar'], and accented characters, emoji and any other Unicode text split exactly like ASCII.

Common patterns

# Count words len("some text here".split()) # 3# Read numbers from one line of input [int(n) for n in input().split()] # user types: 3 7 12 → [3, 7, 12]# Clean each part [p.strip() for p in "a , b , c".split(",")] # ['a', 'b', 'c']# Split and rejoin with a different separator "-".join("a b c".split()) # 'a-b-c'

⚠️ That last one is worth noting: split() and join() are inverses. join() accepts only strings, so a list of numbers needs converting first.

Processing files where the line endings aren’t yours

A CSV uploaded from Windows carries \r\n, and comparisons start failing for no visible reason. Copahost VPS plans give you root access, your choice of Python version, and enough memory to process real files. From €3.99/month, with snapshots.

See VPS plans

Frequently asked questions

What does split() do in Python?

It breaks a string into a list of substrings at each occurrence of a separator. It always returns a list of strings, and if the separator isn’t found, the list contains the original string as its only item.

What’s the difference between split() and split(" ")?

More than it looks. split() with no argument splits on any whitespace, collapses consecutive ones, and ignores leading and trailing space. split(" ") splits at every single space, producing empty strings where spaces repeat or sit at the edges — "a b".split(" ") gives ['a', '', 'b'].

Why does split() return empty strings?

Because you passed an explicit separator and it appeared twice in a row, or at the start or end. The empty string means “nothing was between these two separators” — which in a data file is the difference between a blank field and no field. Filter them with a list comprehension if you don’t need them.

Does split() accept regular expressions?

No. The argument is treated as a literal string — "a1b".split(r"[0-9]") looks for the actual text [0-9]. For patterns, use re.split() from the re module.

How do I limit how many splits happen?

With maxsplit. It limits the splits, not the items — maxsplit=2 produces three items, with the remainder intact in the last one. It’s how you parse key=value when the value may contain the separator.

What’s the difference between split() and rsplit()?

The direction. rsplit() splits from the right, which only matters when maxsplit is used. It’s the right choice for file extensions and paths, where the interesting part is at the end — "archive.tar.gz".rsplit(".", 1) gives ['archive.tar', 'gz'].

When should I use splitlines() instead of split("\n")?

Whenever the text might come from another operating system. splitlines() handles \n, \r\n and \r alike, while split("\n") leaves a stray \r attached to each item on Windows-originated text — a classic cause of comparisons failing invisibly.

What is partition() for?

Splitting on the first occurrence and always returning three items: before, the separator, and after. It never raises — if the separator isn’t found, the last two items are empty. That makes it safe to unpack, unlike split(), which raises ValueError when the count doesn’t match.

Can I use split(",") to read a CSV file?

No, and this is the trap that costs most time. A quoted field containing a comma breaks it — 'a,"b,c",d'.split(",") returns four items instead of three. Use the csv module, which also handles escaped quotes, embedded newlines and different dialects.

Why does "abc".split("") raise an error?

Because an empty separator has no meaning — there’s nothing to split on. Python raises ValueError: empty separator. To get a list of individual characters, use list("abc") instead.

Does split() work with accented characters and emoji?

Yes, normally. There’s no Unicode limitation — "café açúcar".split() returns ['café', 'açúcar'], and any other Unicode text splits exactly like ASCII. Claims to the contrary are simply wrong.

How do I turn the list back into a string?

With join(), which is the inverse operation: "-".join(parts). ⚠️ It accepts only strings, so a list of numbers needs converting first — "-".join(str(n) for n in numbers).

Conclusion

split() is simple until it isn’t, and the boundary is one decision: whether you pass a separator or not.

Three things carry it. split() and split(" ") are different methods in effect — one collapses whitespace and trims the edges, the other splits at every occurrence and hands you empty strings. maxsplit limits splits, not items, which is how you keep a value containing the separator intact. And the argument is always literal — for patterns, re.split() is the tool.

And one rule with no exceptions: don’t parse CSV with split(","). It works until the first quoted field containing a comma, which in real data is usually the first file someone uploads.

Share the Post:
Picture of Gustavo Gallas

Gustavo Gallas

Graduated in Computing at PUC-Rio, Brazil. Specialized in IT, networking, systems administration and human and organizational development​. Also have brewing skills.