What is the re.split() function in Python?
In this shot, we will discuss the re.split() function in Python.
re.split() in Python
The re.split() function belongs to the Regular Expressions (RE) module in Python. The re.split() function basically specifies strings or a set of strings or patterns that matches it.
To use this function, we first need to import the re module.
How re.split() works
The re.split() function splits the given string according to the occurrence of a particular character or pattern. Upon finding the pattern, this function returns the remaining characters from the string in a list.
Syntax
re.split (pattern, string, maxsplit = 0, flags = 0)
Parameters
-
The first parameter,
pattern, denotes the string/pattern where the split will take place. -
The second parameter,
string, denotes the string on which there.split()operation will take place. -
The third parameter,
maxsplit, denotes the number of split operations that should occur. -
The fourth parameter,
flags, helps shorten the code.
Example
flags = re.IGNORECASE ignores case-sensitivity while splitting.
Code
Let’s look at the code snippet below.
# Importing re moduleimport re# Given Strings = "I am a human being."# Performing Splitres_1 = re.split('a', s)res_2 = re.split('a', s, 1)# Print Resultsprint(res_1)print(res_2)
Explanation
-
In line 2, we import the
remodule. -
In line 5, we take a sample string.
-
In line 8, we use the
re.split()function to split the given string with respect to the stringa. -
The output is a list of strings that have been split at points where they came across
a. -
The list contains all the strings except
a. -
In line 9, we introduce the
maxsplitconcept and set it to 1. Therefore, the split only occurs at the firsta. -
In lines 12 and 13, we print the results.
In this way, we can use the re.split() function in Python.