re.split()

christian.dinh's avatar
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 re
text = '**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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy