Python Regular Expression – re.sub() – search and replace string

Spread the love

re.sub() –

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 [1]: import re

In [2]: text = 'Today i spent $100'

In [3]: re.sub('\d+', '0', text)
Out[3]: 'Today i spent $0'

If python does not find a pattern in the string then it returns the original string.

In [4]: re.sub('\d+', '0', 'Today i went to shopping')
Out[4]: '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 [5]: text = 'Today i spent $50 on apple and $50 on mangoes'

In [6]: re.sub('\d+', '0', text)
Out[6]: 'Today i spent $0 on apple and $0 on mangoes'

In [7]: re.sub('\d+', '0', text, count=1)
Out[7]: 'Today i spent $0 on apple and $50 on mangoes'

Rating: 1 out of 5.

Leave a Reply