A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_re_split_method.htm below:

Python re split() method

Python re split() method

The Python re.split() method is used to split a string by occurrences of a specified regular expression pattern. It returns a list of sub-strings.

We can also include optional flags to modify the behavior of the pattern matching. This method is particularly useful for parsing strings where the delimiters are not fixed or when more advanced splitting logic is required.

The str.split() method splits by fixed delimiters where as the re.split() method allows for splitting by complex patterns such as digits, words or any regex-defined pattern.
Syntax

Following is the syntax and parameters of Python re.split() method −

re.split(pattern, string, maxsplit=0, flags=0)
Parameters

Following are the parameters of the python re.split() method −

Return value

This method returns list of sub-strings obtained by splitting the input string according to the specified pattern.

Example 1

Following is the basic example of the python re.split() method. In this example the pattern \s+ splits one or more white space characters of the string −

import re

result = re.split(r'\s+', 'Hello   world!   Welcome to  Python.')
print(result)  
Output
['Hello', 'world!', 'Welcome', 'to', 'Python.']
Example 2

Here in this example we are limiting the number of splits by specifying maxsplit=2 argument in the re.split() method −

import re

result = re.split(r'\s+', 'Hello world! Welcome to Python.', maxsplit=2)
print(result)  
Output
['Hello', 'world!', 'Welcome to Python.']
Example 3

In this example we use the re.VERBOSE flag to allow the regular expression to be written in a more readable way with comments and whites paces −

import re

pattern = re.compile(r"""
    \d+    # One or more digits
    """, re.VERBOSE)
result = pattern.split('abc123def456ghi789')
print(result)  
Output
['abc', 'def', 'ghi', '']
Example 4

This example uses the pattern \b which matches word boundaries by allowing the string to be split at the boundaries of words −

import re

result = re.split(r'\b', 'Hello, world!')
print(result)  
Output
['', 'Hello', ', ', 'world', '!']

python_modules.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4