Python's text split function, str.split(), breaks a string into a list of substrings based on a delimiter you choose. The shortest working example is "a,b,c".split(","), which returns ['a', 'b', 'c']. If you omit the delimiter, Python splits on any run of whitespace and discards empty strings at the ends. This guide covers the syntax, practical examples, and the mistakes that trip people up.

What You'll Need

  • Python 3 installed (any recent version; split() has been stable for years).
  • A way to run Python: the interactive interpreter, a script file, or a notebook.
  • A string you want to break apart, either typed in or read from a file or API response.

Step-by-Step

  1. Open a Python session. Run python3 in a terminal (or python on Windows) to get the >>> prompt, or create a file such as split_demo.py and run it with python3 split_demo.py.
  2. Create a string variable. For example: text = "red,green,blue". Keep the quotes matched; a stray quote is the most common cause of a SyntaxError.
  3. Call split() with a delimiter. Type text.split(","). The result is a list: ['red', 'green', 'blue']. The delimiter itself is removed from the output.
  4. Try splitting on whitespace. Call text.split() with no argument. Python treats any sequence of spaces, tabs, and newlines as one separator, so "a b\tc".split() gives ['a', 'b', 'c']. This is the right choice for splitting words in a sentence.
  5. Limit the number of splits. Pass maxsplit as the second argument: "a:b:c:d".split(":", 2) returns ['a', 'b', 'c:d']. Everything after the second delimiter stays together in the last element. This is useful for parsing lines where only the first field matters.
  6. Split from the right if needed. Use rsplit() with the same arguments to count from the end: "a:b:c:d".rsplit(":", 1) gives ['a:b:c', 'd']. Handy for file extensions or trailing comments.
  7. Split on newlines for multi-line text. Use text.splitlines() rather than split("\n"); it handles Windows \r\n, old Mac \r, and Unix \n line endings consistently and does not leave a trailing empty string.
  8. Clean up the pieces. Splitting usually leaves stray spaces. Apply .strip() to each element: [part.strip() for part in text.split(",")]. This removes leading and trailing whitespace from every item.
  9. Handle empty fields. Consecutive delimiters produce empty strings: "a,,b".split(",") returns ['a', '', 'b']. If you want to drop them, filter with [p for p in parts if p]. If empty fields are meaningful (for example, a CSV column with no value), keep them.
  10. Assign the result. Store the list in a variable: parts = text.split(","). You can then index it (parts[0]), loop over it, or unpack it: first, second, third = parts. Unpacking raises a ValueError if the list length does not match.

Common Mistakes

  • Forgetting that split() returns a list, not a string. Calling string methods like .replace() directly on the result fails; index or loop first.
  • Assuming split() without arguments splits on a single space. It splits on any whitespace run and drops leading/trailing empties. Use split(" ") if you need to preserve empty fields between single spaces.
  • Using split("\n") on files from mixed systems. It leaves \r at the end of each line, which breaks comparisons. Use splitlines().
  • Passing a multi-character delimiter by mistake. split(", ") only splits where a comma is followed by exactly one space; "a, b".split(", ") gives ['a', ' b']. Strip afterwards or use a regular expression.
  • Expecting maxsplit to be the first argument. It is the second: split(delimiter, maxsplit). Swapping them raises a TypeError.
  • Splitting CSV data with split(). Quoted fields containing commas will break. Use the built-in csv module instead.

Tips

  • Chain strip() in a list comprehension rather than looping separately; it is shorter and clearer.
  • Use partition() when you need exactly one split and want the delimiter kept: "key=value".partition("=") returns ('key', '=', 'value').
  • For complex patterns (multiple delimiters, optional spaces), use re.split() from the re module. It is more powerful but slower for simple cases.
  • Check the length of the result before indexing to avoid IndexError on unexpected input.
  • When splitting user input, strip first, then split, then strip each piece; users often add spaces around delimiters.

Troubleshooting

  • Result is a single-element list. The delimiter you passed does not appear in the string. Print the string with repr() to reveal hidden characters such as tabs or non-breaking spaces.
  • Empty strings appear unexpectedly. Consecutive delimiters or leading/trailing delimiters create empty elements. Filter them or use split() with no argument if whitespace is the separator.
  • TypeError: must be str or None, not int. You passed a number as the delimiter. Delimiters must be strings; convert with str() first.
  • ValueError: too many values to unpack. The list has more elements than the variables you assigned. Use maxsplit or index the list instead.
  • Split works but comparisons fail. Hidden whitespace or line endings remain. Apply .strip() to each element and use splitlines() for line-based text.

Frequently Asked Questions

What does split() do when called with no arguments?

It splits on any run of whitespace (spaces, tabs, newlines) and removes empty strings from the start and end of the result. This is the standard way to split a sentence into words.

Can I split on multiple different delimiters at once?

Not with str.split(). Use re.split() with a character class, for example re.split(r"[,;]", text), which splits on commas or semicolons.

How do I keep the delimiter in the output?

Use partition() for a single split, or re.split() with a capturing group. str.split() always removes the delimiter.

Why does split(",") leave spaces in my results?

The delimiter is only the comma; spaces are ordinary characters. Strip each element afterwards, or split on ", " if the format is consistent.

Does split() modify the original string?

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

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

splitlines() splits only on line boundaries and handles all common newline styles. split("\n") splits only on the Unix newline character and can leave carriage returns behind.