The subn method in Python regular expressions
The subn method replaces characters specified in the regular expression and returns a tuple consisting of the result and the number of replacements made. In the first parameter of the method, we specify the regular expression we will search for, in the second parameter - what we will replace it with. In the third parameter, we specify the string. In the fourth optional parameter, we specify the number of replacements:
re.subn(what are we exchanging, what are we exchanging for, where are we exchanging, [number of replacements])
Let's say we have a line:
txt = '123 456 789'
Let's apply the subn method to our string:
txt = '123 456 789'
res = re.subn('\d', '!', txt)
print(res)
After executing the code, the modified line and the number of substitutions made in it will be displayed:
('!!! !!! !!!', 9)
Given a string:
txt = 'aaa bbb 123 www'
Replace all the letters in it that are repeated several times in a row and find out how many replacements were made.
Given a string:
txt = 'aaa @@@ 123w'
Replace all the NOT letters and numbers in it that are repeated several times in a row and find out how many replacements were made.