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.
SyntaxFollowing 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 −
This method returns an iterator of match objects and the number of substitutions.
Example 1Following 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. 2Example 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 1Example 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
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