Python String replace() Method
String replace() in Python returns a copy of the string where occurrences of a substring are replaced with another substring.
Syntax of String replace() method
The replace() method in Python strings has the following syntax:
Syntax: string.replace(old, new, count)
- old – old substring you want to replace.
- new – new substring which would replace the old substring.
- count – (Optional ) the number of times you want to replace the old substring with the new substring.
Return Value : It returns a copy of the string where all occurrences of a substring are replaced with another substring.
Examples of Python replace() Methods
Replace all Instances of a single character using replace() in Python
In this example, we are only replacing a single character from a given string. The Python replace() method is case-sensitive, and therefore it performs a case-sensitive substring substitution, i.e. R in FOR is unchanged.
grrks FOR grrks geeks FOR geeks
Replace all Instances of a String using replace() in Python
Here, we will replace all the geeks with GeeksforGeeks using replace() function.
geeks for geeks geeks for geeks GeeksforGeeks for GeeksforGeeks GeeksforGeeks for GeeksforGeeks
Replace only a certain number of Instances using replace() in Python
In this example, we are replacing certain numbers of words. i.e. “ek” with “a” with count=3.
gaaks for gaaks gaaks gaaks gaaks geas for geas geas geeks geeks
Using a list comprehension and the join() method:
Split the original string into a list of substrings using the split() method.
Use a list comprehension to replace each occurrence of old_substring with new_substring.
Join the list of substrings back into a string using the join() method.
geexs for geexs
Time Complexity: O(n)
Space Complexity: O(n)
Please Login to comment...