How do we use a delimiter to split string in Python regular expression?

PythonServer Side ProgrammingProgramming

The re.split() method

re.split(pattern, string, [maxsplit=0]):

This methods helps to split string by the occurrences of given pattern.

Example

import re
result=re.split(r'a','Dynamics')
print result

Output

['Dyn', 'mics']

Above, we have split the string “Dynamics” by “a”. Method split() has another argument “maxsplit“. It has default value of zero. In this case it does the maximum splits that can be done, but if we give value to maxsplit, it will split the string. 

Example

Let’s look at the example below −

import
result=re.split(r'a','Dynamics Kinematics')
print result

Output

['Dyn', 'mics Kinem', 'tics']

Example

Consider the following code

import re
result=re.split(r'i','Dynamics Kinematics',maxsplit=1)
print result

Output

['Dyn', 'mics Kinematics']

Here, you can notice that we have fixed the maxsplit to 1. And the result is, it has only two values whereas first example has three values.

raja
Published on 11-Jan-2018 12:11:29
Advertisements