Sub topic 11
Splitting on patterns with re.split
This chapter assumes you know how str.split works, can read a simple regular expression (character classes like [,;], \s, \d, and the * and + quantifiers), and are comfortable with lists and for loops.
Why str.split is sometimes not enough
str.split takes a fixed separator. That works when every field is divided by the same literal text. Real input is often messier. A list might be separated by commas, semicolons, or both, with optional spaces after each one. A fixed string cannot describe that.
re.split from the standard re module splits on a pattern instead. Anywhere the pattern matches, the string is cut, and the matched text is removed from the result.
import re
text = "a, b;c,d"
print(re.split(r"[,;]\s*", text)) # ['a', 'b', 'c', 'd']The pattern [,;]\s* matches one comma or semicolon followed by any amount of whitespace. Each match acts as one separator. The call returns a new list and leaves text unchanged.
Capturing groups keep the separators
If the pattern contains a capturing group (parentheses), the text matched by the group is also placed in the result. It appears between the pieces it separated.
import re
print(re.split(r"(\d)", "a1b2c")) # ['a', '1', 'b', '2', 'c']
print(re.split(r"\d", "a1b2c")) # ['a', 'b', 'c']This is useful when you need to know which separator was used, for example when splitting an arithmetic expression into numbers and operators.
import re
expr = "3+4-2"
print(re.split(r"([+-])", expr)) # ['3', '+', '4', '-', '2']Every group adds its text to the list. If you only want grouping for the pattern's structure, use a non-capturing group, written (?:...).
import re
print(re.split(r"(?:,|;)\s*", "a, b;c")) # ['a', 'b', 'c']Empty strings in the result
Like str.split with an explicit separator, re.split keeps empty fields. This happens when a match sits at the start or end of the string, or when two matches are adjacent.
import re
print(re.split(r",", ",a,,b,")) # ['', 'a', '', 'b', '']
print(re.split(r",+", ",a,,b,")) # ['', 'a', 'b', '']The + in the second pattern makes a run of commas count as one separator, which removes the empty string in the middle. The empty strings at the ends remain, because there is a separator at each end. If you do not want them, filter them out.
import re
parts = re.split(r"[,;]", ";a;b;")
clean = [p for p in parts if p]
print(parts) # ['', 'a', 'b', '']
print(clean) # ['a', 'b']Limiting the splits
re.split accepts a maxsplit argument. Pass it by keyword. The older positional form still works, but the keyword is clearer.
import re
print(re.split(r"\s*=\s*", "key = value = more", maxsplit=1))
# ['key', 'value = more']With maxsplit=1, only the first match splits the string and the rest stays intact. A value of 0, the default, means no limit.
Common errors
- Forgetting the raw string prefix. Write
r"\d", not"\d". Withoutr, Python treats the backslash as the start of a string escape. Recent versions warn about unknown escapes, and some sequences such as\bmean something different in a normal string. - Passing the flags as the third positional argument. The signature is
re.split(pattern, string, maxsplit=0, flags=0). A call likere.split(p, s, re.IGNORECASE)setsmaxsplitto the flag's integer value. Useflags=re.IGNORECASE. - Being surprised by capturing groups. A group you added only for alternation changes the output. Use
(?:...)when you do not want its text in the result. - Using a regex when a plain method is enough. For a single fixed separator,
str.splitis simpler and faster.
Choosing between the tools
| Task | Tool |
|---|---|
| One fixed separator | `str.split` |
| Runs of whitespace | `str.split()` with no argument |
| Several separators or optional spacing | `re.split` |
| Keep the separators in the result | `re.split` with a capturing group |
Exercise
Write a call that splits "10 apples, 20 pears;30 plums" into the three item strings, treating a comma or semicolon followed by optional spaces as the separator. Then change the call so the result also contains the separators.
Show answer
Use re.split(r"[,;]\s", "10 apples, 20 pears;30 plums"), which returns ['10 apples', '20 pears', '30 plums']. To keep the separators, wrap the separator characters in a capturing group, as in re.split(r"([,;])\s", "10 apples, 20 pears;30 plums"). That returns ['10 apples', ',', '20 pears', ';', '30 plums']. The spaces after each separator are matched but not captured, so they are dropped.
Exercise
What does re.split(r"(?:-)+", "a--b-c") return, and why does re.split(r"(-)+", "a--b-c") return something different?
Show answer
The first call returns ['a', 'b', 'c']. The non-capturing group adds nothing to the result, and the + makes the run of hyphens one separator. The second call returns ['a', '-', 'b', '-', 'c']. The group is capturing, so its text is included. For the first match "--" the group holds only the last repetition, "-", so you see a single hyphen where two were matched.