re.split()
What You'll Learn: In this tutorial, you'll discover how to use the re.split() function to split a given string at the occurrences of a specified pattern. This helps you break down strings into manageable pieces.
Syntax
The syntax of the re.split() function is:
python
re.split(pattern, string, maxsplit=0, flags=0)
Parameters
- pattern (required): The pattern to be found in the string.
- string (required): The string in which the pattern is to be found.
- maxsplit (optional): The maximum limit on the number of splits.
- flags (optional): Optional flags like
re.IGNORECASE.
Return Value
The function returns a list of split strings.
Examples
- Basic Split with Pattern
Example Code:
pythonimport re pattern = '-+' string = '2344------HELLO--WORLD' result = re.split(pattern, string) print(result)Output:
['2344', 'HELLO', 'WORLD']
- Split String by Space
Example Code:
pythonimport re pattern = '\s+' string = 'Today is a present' result = re.split(pattern, string) print(result)Output:
['Today', 'is', 'a', 'present']
- No Matches
- If there is no matching pattern in the string,
re.split()returns the string as the sole element in the list. Example Code:
pythonimport re pattern = '\s+' string = 'HelloWorld' result = re.split(pattern, string) print(result)Output:
['HelloWorld']
- If there is no matching pattern in the string,
- Maximum Number of Splits
- You can limit the number of splits by specifying the
maxsplitparameter. Example Code:
pythonimport re pattern = '\s+' string = 'Today is a present.' result = re.split(pattern, string, maxsplit=2) print(result)Output:
['Today', 'is', 'a present.']
- You can limit the number of splits by specifying the
Try It Yourself: Fun Exercises
- Split Your Favorite Quote:
- Take a favorite quote and use
re.split()to split it at spaces.
- Take a favorite quote and use
- Separate Words by Dashes:
- Create a string with words separated by multiple dashes and use
re.split()to split the string into individual words.
- Create a string with words separated by multiple dashes and use
Summary:
In this Python tutorial, we learned how to use the re.split() function to split a given string at specified pattern matchings. This function is powerful for breaking down strings into manageable pieces based on patterns. Keep experimenting and have fun with Python!