Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python split() Function: How It Works

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Python's split() method breaks a string into a list of substrings. Called with no arguments, it splits on any run of whitespace and discards leading and trailing whitespace, so "a b\tc\n".split() returns ['a', 'b', 'c']. Called with a separator, it splits on that exact string: "a,b,c".split(",") returns ['a', 'b', 'c']. An optional second argument, maxsplit, limits how many splits are performed. That is the whole function in one line; the rest of this guide covers the details that trip people up.

What You'll Need

  • A working Python 3 installation (any recent 3.x version is fine; the behaviour described here has been stable for years).
  • A way to run Python: the interactive interpreter, IDLE, VS Code, PyCharm, or a terminal with python3.
  • A string to experiment with. You can type one directly at the prompt; no file or package is required.

Note that split() is a string method, not a module function. You do not import anything. If you see code that calls split() on a list or a number, that is a bug, not a missing import.

Step-by-Step

  1. Open a Python prompt or a new script. In a terminal, run python3 (on Windows, python or py usually works). You should see the >>> prompt. Any code below can be typed there or saved in a .py file and run.
  2. Create a string variable. For example: text = "red,green,blue". Strings in Python are immutable, so split() never changes text; it returns a new list.
  3. Call split() with no arguments to split on whitespace. Try "one two three".split(). The result is ['one', 'two', 'three']. Consecutive spaces, tabs and newlines are treated as a single separator, and empty strings at the start or end are dropped. This is the behaviour most people want when parsing words from a line of text.
  4. Pass a separator string to split on something specific. Try "red,green,blue".split(","). The result is ['red', 'green', 'blue']. The separator can be any string, including multi-character ones: "a--b--c".split("--") gives ['a', 'b', 'c']. Unlike the no-argument form, an explicit separator keeps empty strings: "a,,b".split(",") returns ['a', '', 'b'].
  5. Use the maxsplit argument to limit the number of splits. "a,b,c,d".split(",", 2) returns ['a', 'b', 'c,d']. Python performs at most two splits, and the remainder of the string stays together in the final element. This is handy for parsing lines where only the first field is a key and everything after it is the value. You can also pass maxsplit with no separator by using a keyword: "a b c d".split(maxsplit=1) returns ['a', 'b c d'].
  6. Store or inspect the result. The return value is always a list of strings. Assign it: parts = text.split(","), then check len(parts) or index into it with parts[0]. If you only need the first field, text.split(",", 1)[0] avoids building a long list.
  7. Handle the common follow-up: stripping whitespace around fields. Splitting "a, b, c".split(",") gives ['a', ' b', ' c'] because the spaces are part of each field. Clean them with a list comprehension: [p.strip() for p in text.split(",")]. Do not expect split() to trim for you when you pass a separator.
  8. Split from the right if needed. The related method rsplit() works the same way but counts maxsplit from the right. "a.b.c".rsplit(".", 1) returns ['a.b', 'c'], which is useful for file extensions.
  9. Know the related methods. splitlines() splits on line boundaries and is better than split("\n") for text that may use \r\n. partition() splits once and returns a three-tuple of before, separator and after, which is cleaner when you need to keep the separator.

Common Mistakes

  • Passing an empty separator. "abc".split("") raises ValueError: empty separator. If you want individual characters, use list("abc").
  • Expecting split() to modify the original string. It returns a new list; the original is unchanged. Reassign if you want to keep the result: parts = text.split(",").
  • Confusing split() with split(" "). The no-argument version collapses runs of whitespace and drops empty strings; the explicit-space version does not. "a b".split() gives two items, "a b".split(" ") gives three, the middle one empty.
  • Forgetting that maxsplit is positional. split(",", 2) means split at most twice, not split into two pieces. To get exactly two pieces, use split(",", 1) or partition(",").
  • Calling split() on a non-string. Numbers and lists have no split method. Convert first with str(value), or split the string before converting fields with int() or float().
  • Assuming a separator is a regular expression. It is a plain string. For pattern-based splitting, use re.split() from the re module.

Tips

  • Use split() with no arguments for free-form text such as sentences or log lines; it handles tabs and newlines for free.
  • Use split(",") for CSV-style data only when fields cannot contain commas. For real CSV files with quoted fields, use the csv module instead, because split() will break quoted values apart.
  • Chain strip() before or after splitting to avoid stray whitespace: line.strip().split(",").
  • Unpack the result when you know the field count: name, age = "Ada,36".split(","). This raises a clear error if the count is wrong, which is often better than silently indexing.
  • Remember that split() returns strings, so convert numbers explicitly: [int(x) for x in "1,2,3".split(",")].

Troubleshooting

You get one item in the list. The separator you passed does not appear in the string, or you used a character that looks similar but is not the same (for example a comma versus a full-width comma). Print the string with repr(text) to see hidden characters.

You get empty strings. With an explicit separator, consecutive separators produce empty fields, and a leading or trailing separator produces an empty field at that end. Filter them with [p for p in text.split(",") if p] if that is what you want.

You get a ValueError about too many values to unpack. The string contained more separators than you expected. Use maxsplit or partition(), or check len(parts) before unpacking.

You get AttributeError: 'list' object has no attribute 'split'. You are calling split() on something that is already a list. Either split the original string before turning it into a list, or iterate over the list and split each item.

The split looks correct but comparisons fail. Hidden whitespace or carriage returns are usually the cause. Apply .strip() to each field and check with repr().

If that did not work, reduce the problem to a one-line example in the interactive prompt. If the one-liner behaves as expected, the issue is in the surrounding data or code, not in split() itself.

Frequently Asked Questions

Does split() change the original string?

No. Strings are immutable in Python. split() returns a new list and leaves the original string untouched.

What is the difference between split() and split(" ")?

The no-argument form splits on any whitespace, collapses consecutive whitespace and drops empty strings. split(" ") splits only on single spaces and keeps empty fields, so it produces different results for text with double spaces, tabs or newlines.

Can I split on multiple different characters at once?

Not with split() alone. Use re.split(r"[,;]", text) from the re module, or replace the other characters with one separator first.

How do I split a string into exactly two parts?

Use split(separator, 1) or partition(separator). The latter always returns three elements: before, the separator itself, and after.

Why does split() return an empty list?

It does not for a normal string. An empty string "" with no arguments returns [], and "".split(",") returns ['']. If you see [] unexpectedly, the variable is probably empty.

Does split() work on bytes?

Yes, bytes objects have their own split(), but the separator must also be a bytes object, for example b"a,b".split(b","). Mixing str and bytes raises a TypeError.