On this page
re.split
Prev: re.search | Up: re | Next: re.sub
Rel: re.compile, re.error, re.escape, re.findall
Ref: docs.python.org — re.split
Tags: #public #python3 #stdlib #re
Import
import re
from re import split
Signature & Overview
re.split(pattern, string, maxsplit=0, flags=0)
Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all
Usage
import re
assert re.split(r"[,;\s]+", "a, b; c d") == ["a", "b", "c", "d"]
assert re.split(r"[,;]+", "a,b;c", maxsplit=1) == ["a", "b;c"]
Gotchas
- Capturing groups keep delimiters in the result:
re.split(r"(,)", "a,b")returns["a", ",", "b"]—use(?:...)if you don't want the separators included. - Use
str.split()for simple literals: Plainstr.split()is significantly faster when regex features aren't needed.
REPL Inspect
from re import split
help(split)
Linked from
Related notes
- tuts/python3/stdlib_module/re/search Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/sub Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/compile Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/error Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/escape Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/findall Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/finditer shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/fullmatch shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/match shared tags: #re, #stdlib