97 of 151 menu

The sub method of the re module

The sub method of the re module searches for and replaces parts of a string. 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. And the fifth optional parameter specifies flags for additional regular expression settings.

Syntax

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

Example

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

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

Result of code execution:

'b!b'

Example

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

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

Result of code execution:

'b!!!b'

Example

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

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

Result of code execution:

'b!!ab'

See also

  • method subn of module re,
    which returns a tuple of the replaced string and the number of replacements
  • 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