replace() in Python to replace a substring
Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str.
Examples:
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) |
Output:
'helloCworld'
Recommended Posts:
- Python | Replace substring in list of strings
- Python | Pandas Series.str.replace() to replace text in a series
- Python String | replace()
- Python | Replace sublist with other in list
- Python | Pandas dataframe.replace()
- Python | Replace multiple characters at once
- Python | Pandas Series.replace()
- Python | sympy.replace() method
- Python | Pandas Timestamp.replace
- Python | Replace NaN values with average of columns
- Python | Replace negative value with zero in numpy array
- Python | Replace multiple occurrence of character by single
- Map function and Lambda expression in Python to replace characters
- Python | Replace list elements with its ordinal number
- Python String Methods | Set 3 (strip, lstrip, rstrip, min, max, maketrans, translate, replace & expandtabs())
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : vaibhav2992




