Python re.split()
Anonymous contributor
Published Jul 30, 2021Updated Jul 2, 2023
Contribute to Docs
The .split() method of the re module divides a string into substrings at each occurrence of the specified character(s). This method is a good alternative to the default .split() string method for instances that require matching multiple characters.
Syntax
re.split(<pattern>, string, <maxsplit>, <flags>)
A <pattern> is a regular expression that can include any of the following:
- A string:
Jane Smith - A character class code:
/w,/s,/d - A regex symbol:
$,|,^
The other arguments include:
- An integer for the maximum number of splits (max split):
4 - Flags:
IGNORECASE,VERBOSE,DOTALL
Example
The following example illustrates a basic implementation of the .split() method:
import retext = '**Note:** This method only takes positive arguments'print(re.split(r"\*\*|:", text))# The backslashes indicate that the asterisks are part of the pattern
The code will yield:
['', 'Note', '', ' This method only takes positive arguments']
Codebyte Example
The following example is runnable and uses the .split() method to reformat a list of colors:
All contributors
- Anonymous contributor
- Anonymous contributor
CaupolicanDiaz
BrandonDusch- StevenSwiniarski
christian.dinh
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Get a taste of regular expressions (regex), a powerful search pattern language to quickly find the text you're looking for.
- Beginner Friendly.1 hour