re.split()
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
- christian.dinh
- Anonymous contributor
- Anonymous contributor
- CaupolicanDiaz
- BrandonDusch
- StevenSwiniarski
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.