Python provides the regular expression or Regex module as
re . Regex library provides a lot of features where strings can be replaced with regex definitions. The regex library provides the
sub() method for a substitution or replacement. In this tutorial, we examine how to use the replace operation.
re.sub() Method Syntax
In order to replace string with regex, the
re.sub() method is used. The sub() method accepts multiple parameters which are explained below.
- PATTERN is the regex pattern which is searched inside the STRING.
- REPLACEMENT is the string which will be replaced according to PATTERN.
- STRING is the string where replacement procedure done.
- COUNT is the count of replacement. COUNT is optional and if not specified all occurences are replaced.
Replace All Regex Occurences
By default is the
count parameter is not specified for the sub() method all occurrences are replaced according to the specified regex and replacement string. In the following example we replace the names with new names.
import re str = "Ali likes to live in Ankara." print(re.sub('A','a',str))
ali likes to live in ankara.
We can also replace multiple strings with a single string. The
| sign is used to specify multiple strings.
import re str = "Ali, Ahmet and Elif like to live in Ankara." print(re.sub('Ali|Ahmet|Elif','NAME',str))
NAME, NAME and NAME like to live in Ankara.
Replace Specified Regex One Time
The count parameter of the sub() method can be used to specify the replacement count if the specified regex is matched multiple times. In the following example, we replace the character A just one time.
import re str = "A, A and A like to live in Ankara." print(re.sub('A','NAME',str,count=1))
NAME, A and A like to live in Ankara.
Replace Specified Regex Multiple Times
The count parameter can be also used to replace specified regex multiple times but not for all occurrences. In the following example, we change character A just 2 times.
import re str = "A, A and A like to live in Ankara." print(re.sub('A','NAME',str,count=2))
NAME, NAME and A like to live in Ankara.