Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

replace() in Python to replace a substring

  • Difficulty Level : Basic
  • Last Updated : 23 Nov, 2020

Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str.


 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Input  : str = "helloABworld"
Output : str = "helloCworld"

Input  : str = "fghABsdfABysu"
Output : str = "fghCsdfCysu"

This problem has existing solution please refer Replace all occurrences of string AB with C without using extra space link. We solve this problem in python quickly using replace() method of string data type.

How does replace() function works ?
str.replace(pattern,replaceWith,maxCount) takes minimum two parameters and replaces all occurrences of pattern with specified sub-string replaceWith. Third parameter maxCount is optional, if we do not pass this parameter then replace function will do it for all occurrences of pattern otherwise it will replace only maxCount times occurrences of pattern.

# Function to replace all occurrences of AB with C
def replaceABwithC(input, pattern, replaceWith):
    return input.replace(pattern, replaceWith)
# Driver program
if __name__ == "__main__":
    input   = 'helloABworld'
    pattern = 'AB'
    replaceWith = 'C'
    print (replaceABwithC(input,pattern,replaceWith))


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!