Explain subn Methods of re Module in Python



A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The re module in python refers to the module Regular Expressions (RE). It specifies a set of strings or patterns that matches it. Metacharacters are used to understand the analogy of RE. 

subn()method is similar to sub() and also returns the new string along with the no. of replacements.

Syntax

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

Example

import re
print(re.subn('ov', '~*' , 'movie tickets booking in online'))
t = re.subn('ov', '~*' , 'movie tickets booking in online', flags = re.IGNORECASE)
print(t)
print(len(t))
print(t[0])

Here you can see that, subn() method It returns a tuple with count of total of all the replacements as well as the new string.

Output

('m~*ie tickets booking in online', 1)
('m~*ie tickets booking in online', 1)
2
m~*ie tickets booking in online
Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements