In this section, we will learn what String replace() method is and how to use it in Python.
What is String replace() Method in Python?
The Python string replace() method is used to replace a sub-string in a string value with another value.
Note: this method does not change the original string value but instead creates a new one and returns that as a result.
Python String replace() Method Syntax:
string.replace(oldValue, newValue, count)
String replace() Method Parameter
The method takes 3 arguments:
- The first argument is the sub-string in the target string that we want to replace it with a new value.
- The second argument is the new value that we want to be used as the replacement for the old value.
- The third argument, which is optional, is the number of occurrences for the old value (the first argument of the method) that should be replaced with the new value (the second argument). The default is set to all occurrences.
String replace() Method Return Value
The return value of this method is a new string with old value (the first argument) being replaced with the new one.
Example: python replace character in string
s1= "they know we know that they know we know" result = s1.replace("they know", "she knows") print(result)
Output:
she knows we know that she knows we know
Example: python replace char in string
s1= "this is a sentence" result = s1.replace("t", "T",1) print(result)
Output:
This is a sentence
Example: python string substitution
s1= "Hello you" result = s1.replace("you", "World") print(result)
Output:
Hello World