Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python re subn() method



The Python re.subn() method is similar to re.sub() method but this returns both the modified string and the count of substitutions made. It performs a search and replace operation on a string using a regular expression pattern. The modified string with replacements is returned along with the count of substitutions.

This method is useful when we need to know how many replacements were made in addition to obtaining the modified string. This method often used when we need both the modified string and the substitution count for further processing.

Syntax

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

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

Parameters

Below are the parameters of the python re.subn() method −

  • pattern: The regular expression pattern to search for.
  • repl: The replacement string or a function to be called for each match.
  • string: The input string to perform the substitution on.
  • count(optional): Maximum number of substitutions to make. The default is 0 which means replace all occurrences.
  • flags(optional): Flags to modify the matching behavior (e.g., re.IGNORECASE)

Return value

This method returns an iterator of match objects and the number of substitutions.

Example 1

Following is the basic example of the python re.subn() method, in which all numeric sequences in the string are replaced with the string 'number' and also returns the count of substitutions made −

import re

result, count = re.subn(r'\d+', 'number', 'There are 123 apples and 456 oranges.')
print(result)  
print(count)     

Output

There are number apples and number oranges.
2

Example 2

This example uses capturing groups in both the pattern and the replacement string to rearrange a date format. Here only one substitution is made so count is 1.

import re

result, count = re.subn(r'(\d+)-(\d+)-(\d+)', r'\3/\2/\1', 'Date: 2022-01-01')
print(result)  
print(count)      

Output

Date: 01/01/2022
1

Example 3

Here in this example a function square is used as the replacement. It squares each numeric match found in the string returns the substitution count as 5 −

import re

def square(match):
    num = int(match.group())
    return str(num ** 2)

result, count = re.subn(r'\d+', square, 'Numbers: 1 2 3 4 5')
print(result) 
print(count)        

Output

Numbers: 1 4 9 16 25
5
python_modules.htm
Advertisements