Sub topic 11
Splitting on patterns with re.split
str.split handles a fixed separator. Real text often needs a rule instead: "a comma or semicolon, with optional spaces", "any run of digits", "the end of a sentence". re.split from the standard re module splits on a regular expression. This chapter covers how it differs from str.split, how capturing groups change its output, and the edge cases that surprise people.
This chapter assumes you know basic regular expression syntax (character classes, +, *, groups, \s, \d), the behaviour of str.split and str.join, and how to read a list of strings.
The signature and the basic idea
re.split(pattern, string, maxsplit=0, flags=0)The function scans string for non-overlapping matches of pattern. It returns the text between those matches as a list. The matched text itself is discarded unless the pattern contains a capturing group.
import re
print(re.split(r"[,;]\s*", "a, b;c,d")) # ['a', 'b', 'c', 'd']The pattern [,;]\s* matches one comma or semicolon plus any spaces after it. Each match is one separator, and the pieces between matches go into the list.
Pass maxsplit and flags by keyword. Python 3.13 deprecates passing them positionally, and keywords make the call easier to read.
import re
print(re.split(r"\s*[:=]\s*", "key = value: more", maxsplit=1))
# ['key', 'value: more']
print(re.split(r"and", "A AND b", flags=re.IGNORECASE))
# ['A ', ' b']maxsplit works as it does in str.split: at most that many splits happen, and the rest of the string stays in the last item. A value of 0 means no limit.
If you reuse a pattern, compile it once. A compiled pattern has its own split method with the same behaviour:
import re
SEPARATOR = re.compile(r"[,;]\s*")
print(SEPARATOR.split("x, y;z")) # ['x', 'y', 'z']Regular expression special characters
str.split(".") treats the dot literally. re.split(".", ...) treats it as "any character", so every character is a separator:
import re
print("a.b".split(".")) # ['a', 'b']
print(re.split(".", "a.b")) # ['', '', '', '']
print(re.split(r"\.", "a.b")) # ['a', 'b']When the separator comes from a variable or user input, use re.escape so it is matched literally:
import re
sep = "|"
print(re.split(re.escape(sep), "a|b|c")) # ['a', 'b', 'c']If the separator is a single fixed string, str.split is simpler and faster. Use re.split only when you need a pattern.
Empty strings at the edges
Like str.split(","), re.split keeps empty strings. When a match sits at the very start or end of the text, you get an empty item there. Consecutive separators give empty items between them.
import re
print(re.split(r"\s+", " hello world ")) # ['', 'hello', 'world', '']
print(re.split(r",", "")) # ['']This is the key difference from str.split() with no argument, which drops leading and trailing whitespace. There are two common fixes:
import re
text = " hello world "
# Strip first, then split.
print(re.split(r"\s+", text.strip())) # ['hello', 'world']
# Or drop empty items afterwards.
print([p for p in re.split(r"\s+", text) if p]) # ['hello', 'world']For plain whitespace, text.split() does both jobs. Reach for re.split when the separator is something other than whitespace.
Filtering empty items is not always correct. In delimited data such as "a,,c", an empty field is real information. Filter only when empty pieces are noise.
Capturing groups keep the separators
If the pattern contains a capturing group, the text matched by the group is placed in the result between the pieces.
import re
print(re.split(r"(\d)", "a1b2c")) # ['a', '1', 'b', '2', 'c']This is how you tokenise text. You split on operators and keep them:
import re
def tokens(expr):
parts = re.split(r"\s*([+\-*/()])\s*", expr)
return [p for p in parts if p]
print(tokens("3 + 4*(2 - 1)"))
# ['3', '+', '4', '*', '(', '2', '-', '1', ')']The \s* on each side absorbs spaces, so they do not appear in the output. The group contains only the operator. The filter removes the empty strings that appear when two separators are adjacent, such as * followed by (.
With a single group around the whole separator, the result alternates between content and separator. The items at even indexes are the pieces, and the items at odd indexes are the separators. Joining the result gives back the original text, which makes a round trip with "".join possible:
import re
original = "3+4*2"
parts = re.split(r"([+\-*/])", original)
print(parts) # ['3', '+', '4', '*', '2']
print("".join(parts) == original) # TrueGroups you did not mean to capture
Parentheses capture by default, so grouping an alternation adds items to your result you may not want:
import re
text = "x and y or z"
print(re.split(r"\s+(and|or)\s+", text))
# ['x', 'and', 'y', 'or', 'z']
print(re.split(r"\s+(?:and|or)\s+", text))
# ['x', 'y', 'z']Use a non-capturing group, (?:...), when you need parentheses only for grouping. Check how many capturing groups the pattern has before you trust the shape of the result.
Groups that did not take part in the match
If a pattern has several groups and only some matched, the others contribute None:
import re
print(re.split(r"(-)|(\+)", "a-b+c"))
# ['a', '-', None, 'b', None, '+', 'c']Every match adds one item per group, whether or not the group participated. Code that expects strings will fail on None, for example "".join(parts) raises TypeError. Prefer one outer group or non-capturing groups where you can.
The following diagram summarises how the pattern shapes the result.
Empty matches and zero-width patterns
A pattern can match the empty string, for example x* or a lookahead. Since Python 3.7, re.split splits on empty matches too. Before 3.7 it ignored them, so check your minimum Python version if the code must run on old interpreters.
Zero-width splitting is useful when you want to cut at a position without consuming characters. A lookahead splits camel case names:
import re
print(re.split(r"(?=[A-Z])", "camelCaseString"))
# ['camel', 'Case', 'String']A lookbehind splits after sentence-ending punctuation while keeping the punctuation with its sentence:
import re
text = "Hi. How are you? Fine!"
print(re.split(r"(?<=[.!?])\s+", text))
# ['Hi.', 'How are you?', 'Fine!']Both patterns match something that is zero-width or whitespace only, so no letters are lost. Two cautions apply to zero-width patterns.
- A pattern that can match empty at the string start gives a leading empty string. Splitting
"CamelCase"with(?=[A-Z])returns['', 'Camel', 'Case']. - A pattern that can match both empty and non-empty text, such as
x*, produces extra empty items around the real matches:
import re
print(re.split(r"x*", "axb")) # ['', 'a', '', 'b', '']If you see unexpected empty strings, check whether the pattern can match nothing. Changing * to + usually fixes it.
Choosing between the splitting tools
| Situation | Tool |
|---|---|
| Fixed separator, such as `","` | `str.split(",")` |
| Runs of whitespace, ignore the edges | `str.split()` |
| Cut at the first or last separator only | `partition`, `rpartition`, or `maxsplit` |
| Separator is a pattern, or one of several | `re.split` |
| Need to keep the separators | `re.split` with a capturing group |
| Fields may be quoted and contain the separator | `csv` module |
str.split is faster than re.split for fixed strings, and its intent is clearer. A regular expression is harder to read and easier to get wrong, so use it only when a fixed separator cannot express the rule.
re.split only describes where the separators are. It does not understand nesting or quotes. Splitting 'a,"b,c",d' with re.split(",", ...) breaks the quoted field. Patterns that try to skip commas inside quotes become fragile quickly, so use the csv module for that case, as the last chapter of this tutorial shows.
A worked example: parsing a mixed log field
A tag field uses commas, semicolons or pipes as separators, with inconsistent spacing. You want a clean list, with empty entries removed, and the original order kept.
import re
TAG_SEPARATOR = re.compile(r"\s*[,;|]\s*")
def parse_tags(field):
parts = TAG_SEPARATOR.split(field.strip())
return [p for p in parts if p]
print(parse_tags(" red , green;blue|| yellow "))
# ['red', 'green', 'blue', 'yellow']
print(parse_tags(""))
# []Three decisions make this correct:
- The pattern is compiled once at module level, because the function may run many times.
field.strip()removes whitespace that sits outside any separator, so no entry is made of spaces only.- The comprehension drops empty strings, including the single
['']thatre.splitreturns for empty input.
To produce clean output text from the list, you can join it again with ", ".join(parse_tags(...)). That normalises all three separators into one.
Common errors
- Forgetting the raw string. Write patterns as
r"\s+". In a normal string, sequences such as\bare interpreted as escape characters beforeresees them. - Unescaped literal separators. A dot, pipe, plus or parenthesis in a separator needs
re.escapeor a backslash. - Unexpected groups. Adding parentheses changes the output shape. Use
(?:...)for grouping only. - Not handling
None. Several groups can produceNoneitems. - Treating empty items as errors. Leading, trailing and doubled separators produce empty strings by design.
- Using
re.splitwherestr.splitis enough. It costs readability and speed for no gain.
Exercise
What does re.split(r"(,)\s*", "a, b,c") return, and how would you change the pattern so the commas are not included?
Show answer
It returns ['a', ',', 'b', ',', 'c'], because the capturing group (,) adds each matched comma to the result. To exclude the commas, remove the capturing group, or make the group non-capturing: re.split(r",\s*", "a, b,c") returns ['a', 'b', 'c'].
Exercise
Write a function split_sentences(text) that splits on whitespace that follows ., ! or ?, keeping the punctuation with each sentence. What does it return for "One. Two? Three!", and why does it use a lookbehind instead of a capturing group?
Show answer
import re then def split_sentences(text): return re.split(r"(?<=[.!?])\s+", text). For "One. Two? Three!" it returns ['One.', 'Two?', 'Three!']. The lookbehind (?<=[.!?]) checks the previous character without consuming it, so the punctuation stays in the preceding piece. A capturing group would insert the punctuation as separate list items and consume it from the sentence.