What is the re.subn() function in Python?

re.subn() belongs to the regular expressions (RE) module in Python and specifies strings or a set of strings or patterns that match it. To use this function, we need to import the RE module.

The re.subn() function is the same as the re.sub() function, except that it also provides a count of the number of replacements that it has done.

Syntax

re.subn(pattern, repl, string, count=0, flags=0)
  • The first parameter, pattern, denotes the string/pattern that needs to be replaced.

  • The second parameter, repl, denotes the string/pattern with which the pattern is replaced.

  • The third parameter, string, denotes the string on which the re.subn() operation will take place.

  • The fourth parameter, count, denotes the number of replacements that should occur on which the re.subn() operation will take place.

  • The fifth parameter, flags, helps to shorten the code and has similar functions as that of split operations.

Code

Let us look at the code snippet below:

# Importing re module
import re
# Given String
s = "I am a human being."
# Performing the subn() operation
res_1 = re.subn('a', 'x', s)
res_2 = re.subn('[a,I]','x',s)
# Print Results
print(res_1)
print(res_2)

Explanation

  • In line 2, we import the re module.

  • In line 5, we take a sample string.

  • In line 8, we use the re.subn() function to replace all the a’s with x’s in the string s. Since the number of replacements is three, it has been provided in the tuple as an output.

  • In line 9, we use the re.subn() function to replace all the a’s and I’s with x’s in the string s. Since the number of replacements is four, it has been provided in the tuple as an output.

  • In lines 12 and 13, we print the results.

Free Resources