98 of 151 menu

The subn method of re module

The subn method of the re module searches for and replaces parts of a string. The method returns a tuple of the new string and the number of replacements made in it. The first parameter is a regular expression, and the second is the substring to replace with. The third parameter specifies the string to replace. The fourth optional parameter specifies the number of replacements. The fifth optional parameter specifies flags for additional regular expression settings.

Syntax

import re re.subn(regular expression, replacement, string, [number of replacements], [flags bunting])

Example

Let's find and replace the symbol 'a':

txt = 'bab' res = re.subn('a', '!', txt) print(res)

Result of code execution:

('b!b', 1)

Example

By default, all matches found are replaced. Let's replace the 'a' character in the string again:

txt = 'baaab' res = re.subn('a', '!', txt) print(res)

Result of code execution:

('b!!!b', 3)

Example

Now let's make just two substitutions in the line:

txt = 'baaab' res = re.subn('a', '!', txt, 2) print(res)

Result of code execution:

('b!!ab', 2)

See also

  • method sub of module re,
    which searches and replaces parts of a string
  • method findall of module re,
    which returns a list of all matches in a string
  • method finditer of module re,
    which returns an iterator of all matches of the regular expression in the string
  • method search of module re,
    which looks for the first match of a regular expression in a string
  • method match of module re,
    which looks for a match with a regular expression at the beginning of a line
  • method fullmatch of module re,
    which looks for all matches of a regular expression in a string
byenru