The re.sub() function search a pattern in a string and replace it with another string.
syntax of re.sub() –
re.sub(pattern, replace, string, count=0, flags=0)
pattern – pattern to match a string
replace – the sub string to replace the old string
string – the actual string within which to search
count (optional) – how many occurrences of the matches string to replace. By default it is 0 means it will replace all occurrences.
flags (optional) – to modify the behavior of the function.
Let’s say that you want to replace every number with a zero.
In : import re In : text = 'Today i spent $100' In : re.sub('\d+', '0', text) Out: 'Today i spent $0'
If python does not find a pattern in the string then it returns the original string.
In : re.sub('\d+', '0', 'Today i went to shopping') Out: 'Today i went to shopping'
To replace only a specified number of occurrences of matched pattern, use the count flag. Let’s say you want to only replace one occurrences of numbers in a string.
In : text = 'Today i spent $50 on apple and $50 on mangoes' In : re.sub('\d+', '0', text) Out: 'Today i spent $0 on apple and $0 on mangoes' In : re.sub('\d+', '0', text, count=1) Out: 'Today i spent $0 on apple and $50 on mangoes'