Smart Systems for Home

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

Python String x split: How to Split Strings

· 5 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

You split a Python string with the split() method: text.split(sep) breaks the string at every occurrence of sep and returns a list of pieces. Called with no arguments, text.split() splits on any run of whitespace and drops empty strings. That one line is the whole answer for most cases; the rest of this guide covers the arguments, the edge cases that surprise people, and how to fix the results when they look wrong.

What You'll Need

  • A working Python 3 installation (any recent 3.x is fine; split() has behaved the same way for years).
  • A way to run code: the interactive interpreter, a script file, or a notebook.
  • A string to practise on. Any sentence or comma-separated line works.

Step-by-Step

  1. Start with the default split. Call split() with no arguments to break a sentence into words: "the quick brown fox".split() returns ['the', 'quick', 'brown', 'fox']. This form treats spaces, tabs and newlines all as separators and collapses repeated whitespace, so "a b".split() gives ['a', 'b'], not an empty string in the middle.
  2. Pass an explicit separator when the format is fixed. For comma-separated data use "a,b,c".split(","), which returns ['a', 'b', 'c']. The separator can be any string, not just one character: "a::b::c".split("::") returns ['a', 'b', 'c']. Unlike the whitespace form, an explicit separator does not collapse repeats: "a,,b".split(",") returns ['a', '', 'b'], with an empty string where the data is missing.
  3. Limit the number of splits with maxsplit. The second argument caps how many times the string is cut: "a,b,c,d".split(",", 2) returns ['a', 'b', 'c,d']. Everything after the second cut stays in the final element. This is the standard way to peel a key off a value, such as splitting "name=Jane Doe" on "=" with maxsplit=1 so the value keeps its internal spaces.
  4. Handle extra whitespace around fields. Splitting "a, b, c" on a comma leaves spaces on the pieces. Either strip each one with a list comprehension, [part.strip() for part in text.split(",")], or split on ", " if the spacing is guaranteed. The comprehension is safer because it also copes with tabs and stray spaces.
  5. Split from the right when the tail matters. rsplit() works like split() but counts from the end. "a.b.c".rsplit(".", 1) returns ['a.b', 'c'], which is what you want for file extensions or the last path segment.
  6. Split on line breaks. Use splitlines() rather than split("\n") when reading text that may come from Windows or a mix of systems. It handles \n, \r\n and \r and does not leave a trailing empty element when the text ends with a newline.
  7. Check the result before indexing. split() always returns a list, but the length varies with the input. Print it or check len() before reaching for parts[1], otherwise a line with no separator raises IndexError.
  8. Unpack when the shape is known. If you are certain there are exactly two fields, key, value = line.split("=", 1) is concise and fails loudly with ValueError if the data does not match. That failure is usually better than silently indexing the wrong element.

Common Mistakes

  • Expecting split(" ") to behave like split(). An explicit space separator keeps empty strings for repeated spaces and does not treat tabs or newlines as separators. Use the no-argument form for free-form text.
  • Forgetting that split() returns a list, not a string. Calling .upper() or concatenating straight onto the result fails; index or join first.
  • Using a multi-character separator and expecting a regex. split() matches literal text only. Patterns such as "comma or semicolon" need the re module, for example re.split(r"[,;]", text).
  • Assuming the last field is present. Trailing separators produce a trailing empty string: "a,b,".split(",") gives ['a', 'b', '']. Filter or validate before using the values.
  • Confusing split() with strip(). Splitting divides the string; stripping removes characters from the ends. They are often used together but do different jobs.

Tips

  • Use maxsplit whenever the right-hand side may itself contain the separator. It is the difference between a clean key-value split and a mangled value.
  • For CSV files, prefer the built-in csv module over split(","). It handles quoted fields that contain commas, which plain splitting cannot.
  • Remember that strings are immutable: split() never changes the original, it returns a new list.
  • When debugging, print repr(parts) rather than parts so invisible characters such as tabs and trailing spaces show up.
  • If you need to keep the separators, use re.split() with a capturing group; split() always discards them.

Troubleshooting

The list has unexpected empty strings. You are using an explicit separator and the input contains repeated or trailing separators. Either filter them out with [p for p in parts if p] or switch to the whitespace form if the data is space-separated.

IndexError when reading a field. The line did not contain the separator, so the list is shorter than expected. Check with len(parts) and handle the short case before indexing.

ValueError: too many values to unpack. The string contained more separators than the number of variables. Add maxsplit so the remainder stays in one element, or unpack into a list instead.

Nothing splits at all. The separator does not match the actual characters. Print repr(text) to reveal hidden tabs, non-breaking spaces or different quote characters, then split on the real character.

The split works but values have spaces. Strip each element, or split on the separator plus space if the format is strictly controlled.

Frequently Asked Questions

What does split() return?

A list of strings. With no arguments it splits on runs of whitespace; with a separator it splits at every literal occurrence of that separator.

How do I split only the first occurrence?

Pass maxsplit=1 as the second argument: text.split("=", 1). Use rsplit("=", 1) to split only the last occurrence.

Can I split on multiple different characters at once?

Not with split(), which takes one literal separator. Use re.split() from the re module with a character class such as r"[,;]".

Why does split(",") leave empty strings?

Because an explicit separator is matched literally and repeated separators create empty fields. The no-argument whitespace form collapses repeats instead.

How do I split a string into individual characters?

Convert it to a list with list(text), or call text.split() only if you want words. There is no need to pass an empty separator, which raises ValueError.

Does split() modify the original string?

No. Strings are immutable, so the method returns a new list and leaves the original untouched.