re.sub()

What You'll Learn: In this tutorial, you'll discover how to use the re.sub() function to replace one or many matches of a pattern in a string with another string. This function is useful for editing and cleaning up text.

Syntax

The syntax of the re.sub() function is:

python
re.sub(pattern, repl, string, count=0, flags=0)

Parameters

  • pattern (required): The pattern to be found in the string.
  • repl (required): The value to replace in the string in place of the matched pattern.
  • string (required): The string in which the replacement is to be done.
  • count (optional): The maximum number of pattern occurrences to be replaced.
  • flags (optional): Optional flags like re.IGNORECASE.

Return Value

The function returns a new string with the replacements.

Examples

  1. Replace Pattern Matchings with Replacement String
    • Example Code:

      python
      import re
      
      pattern = '[0-9]+'
      string = 'Account Number - 12345, Amount - 586.32'
      repl = 'NN'
      
      print('Original string')
      print(string)
      
      result = re.sub(pattern, repl, string)
      
      print('After replacement')
      print(result)
      
    • Output:

       
      Original string
      Account Number - 12345, Amount - 586.32
      After replacement
      Account Number - NN, Amount - NN.NN
      
  2. Limit Maximum Number of Replacements
    • Example Code:

      python
      import re
      
      pattern = '[0-9]+'
      string = 'Account Number - 12345, Amount - 586.32'
      repl = 'NN'
      
      print('Original string')
      print(string)
      
      result = re.sub(pattern, repl, string, count=2)
      
      print('After replacement')
      print(result)
      
    • Output:

       
      Original string
      Account Number - 12345, Amount - 586.32
      After replacement
      Account Number - NN, Amount - NN.32
      
  3. Using Optional Flags
    • Example Code:

      python
      import re
      
      pattern = '[a-z]+'
      string = 'Account Number - 12345, Amount - 586.32'
      repl = 'AA'
      
      print('Original string')
      print(string)
      
      result = re.sub(pattern, repl, string, flags=re.IGNORECASE)
      
      print('After replacement')
      print(result)
      
    • Output:

       
      Original string
      Account Number - 12345, Amount - 586.32
      After replacement
      AA AA - 12345, AA - 586.32
      

Try It Yourself: Fun Exercises

  1. Edit Your Favorite Quote:
    • Take a favorite quote and use re.sub() to replace specific words.
  2. Clean Up Text:
    • Create a string with messy text and use re.sub() to replace unwanted characters.

Summary:

In this Python tutorial, we learned how to use the re.sub() function to replace matches of a given pattern in a string with a replacement string. This function is powerful for editing and cleaning up text. Keep experimenting and have fun with Python!