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

  1. Basic Split with Pattern
    • Example Code:

      python
      import re
      
      pattern = '-+'
      string = '2344------HELLO--WORLD'
      result = re.split(pattern, string)
      print(result)
      
    • Output:

       
      ['2344', 'HELLO', 'WORLD']
      
  2. Split String by Space
    • Example Code:

      python
      import re
      
      pattern = '\s+'
      string = 'Today   is a   present'
      result = re.split(pattern, string)
      print(result)
      
    • Output:

       
      ['Today', 'is', 'a', 'present']
      
  3. 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:

      python
      import re
      
      pattern = '\s+'
      string = 'HelloWorld'
      result = re.split(pattern, string)
      print(result)
      
    • Output:

       
      ['HelloWorld']
      
  4. Maximum Number of Splits
    • You can limit the number of splits by specifying the maxsplit parameter.
    • Example Code:

      python
      import re
      
      pattern = '\s+'
      string = 'Today is a present.'
      result = re.split(pattern, string, maxsplit=2)
      print(result)
      
    • Output:

       
      ['Today', 'is', 'a present.']
      

Try It Yourself: Fun Exercises

  1. Split Your Favorite Quote:
    • Take a favorite quote and use re.split() to split it at spaces.
  2. Separate Words by Dashes:
    • Create a string with words separated by multiple dashes and use re.split() to split the string into individual words.

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!