Skip to main content

Python RegEx sub() Functions

The re.sub() function is used to replace occurrences of a particular sub-string with another sub-string.


import re
res=re.sub(pattern, repl, string, count=0, flags=0)

The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd parameter), count checks and maintains the number of times this occurs. 


import re
str = "Welcome to Python Programming"
res = re.sub("\s", " !! ", str, 1)

Output: Welcome !! to Python Programming

Submitted by devanshi.srivastava on July 17, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.