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 modulere
,
which returns a tuple of the replaced string and the number of replacements -
method
findall
of modulere
,
which returns a list of all matches in a string -
method
finditer
of modulere
,
which returns an iterator of all matches of the regular expression in the string -
method
search
of modulere
,
which looks for the first match of a regular expression in a string -
method
match
of modulere
,
which looks for a match with a regular expression at the beginning of a line -
method
fullmatch
of modulere
,
which looks for all matches of a regular expression in a string