The split method of the re module
The split method of the re module splits a string and returns the resulting list. The first parameter is a regular expression. The second parameter specifies the string we want to split. The third optional parameter specifies the maximum number of parts to split. The fourth optional parameter specifies flags for additional regular expression settings.
Syntax
import re
re.split(regular expression, string, [max. number of parts], [flags bunting])
Example
Let's split the line at the hyphen:
txt = 'aaa-bbb-123 456'
res = re.split('-', txt)
print(res)
Result of code execution:
['aaa', 'bbb', '123 456']
Example
Now let's split the line at the hyphen twice:
txt = 'aaa-bbb-123-456'
res = re.split('-', txt, 2)
print(res)
As can be seen from the code execution result, the string was split at the hyphen only into two parts. And the third part of the string included its remainder:
['aaa', 'bbb', '123-456']
See also
-
method
findallof modulere,
which returns a list of all matches in a string -
method
finditerof modulere,
which returns an iterator of all matches of the regular expression in the string -
method
searchof modulere,
which looks for the first match of a regular expression in a string -
method
matchof modulere,
which looks for a match with a regular expression at the beginning of a line -
method
fullmatchof modulere,
which looks for all matches of a regular expression in a string