The Python function re.sub(pattern, replacement, string)
returns the modified string with the matched pattern replaced with the replacement. Is there any easy way to check whether a match has occurred and a modification has been made? (And also, how many modifications)
re. sub() function is used to replace occurrences of a particular sub-string with another sub-string. This function takes as input the following: The sub-string to replace.
sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string.
If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.
The count argument will set the maximum number of replacements that we want to make inside the string. By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.
Depends on the version. In Python <= 2.6, you have to couple sub()
with match()
or search()
to get count.
If you are using Python >= 2.7, you can use subn()
, which will return a tuple of (new_string, number_of_subs_made)
.
For example:
>>> import re
>>> re.subn('l', 'X', "Hello World!")
('HeXXo WorXd!', 3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With