In this tutorial, we’ll learn what Python string replace() method is and how to properly use it. We’ll go through multiple Python code examples to understand how replace method works.
Introduction: Python String replace() Method
This method returns a new string having all the characters/string replaced with the string/character passed as an argument.
Syntax of replace() Method
string.replace(originalString(required), replacingString(required), number(optional))
- Python string replace method can take up to three parameters.
- First parameter is the character/string that is to be replaced.
- Second parameter is the character/string that will replace the original character/string.
- Third argument is optional. It’s used to specify the number of items that will be replaced. Python string replace method will replace all the specified items if no range is given.
- This method returns the old string values if specified characters are not found.
Example 1: replace() Method applied on a Python String
print( 'This is Python'.replace('is', 'are') ) print( 'This is Python'.replace('is', 'are', 1) ) print( 'This is Python'.replace('is', 'are', 0) ) print( 'This is Python'.replace('is', 'are', 4) ) print( 'This is Python'.replace('Pyth', 'Program')) print( 'This is Python3'.replace('3', '5') ) print( 'This is Python'.replace('Program', 'Language') )
Output
Thare are Python Thare is Python This is Python Thare are Python This is Programon This is Python5 This is Python
This is how Python string replace method works. You can try it with even more examples to better understand the working of this method.
Example 2: Python String replace() Method Return Value
val= 'Python Programming Python Language' returnedVal=val.replace('Pyt','Programming',1) print(returnedVal) print(val)
Output
Programminghon Programming Python Language // replaced item string Python Programming Python Language // original string
We can see that Python string replace method has returned a new string.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string replace method. I’d be very happy to receive your feedback on this post. Thank you for reading it.