How Can We Help?
In this tutorial, we will explain how to use Python string replace() method with basic syntax by example for better understanding.
How to Replace String in Python? To replace a string in Python, we use the replace() method. The replace method in Python is used to replace old string values with a new string value. It returns a copy of the string with all occurrences of the old value replaced by the new value. This function is a built-in function used for string handling.
Syntax:
<string_value/string_variable>.replace(old value, new value)
Input Parameters:
- string / String variable : The string that we want to replace the old value by the new one.
- old : This is old value to be replaced.
- new : This is the new value, which would replace old value
Python String Replace Substring
We can replace a substring value of a string by using replace() built-in in Python.
Example (1)
#Print the result of join() method
str1='ramini'
print('New string variable value:',str1.replace ('r','l'))
print('New string value:','python'.replace('p','C'))
Output of example (1)
New string variable value: lamini
New string value: Cython
In the above example, we have replaced “r” with “l” in string variable str1, so resulted in the string is “lamini” and “p” with “C” in string value ‘python’, so the resulted string is ‘Cython’.
In this tutorial, you have learned the string replace() method in Python. What is it? And how to replace an old value by the new value in a string variable.
Hopefully, it was clear and concise.
If you have an inquiry or doubt, don’t hesitate to leave them in a comment. We are waiting for your valuable feedback.
Similar Python String Manipulation Methods:
- count() : It counts how many times a given substring occurs in a string between the given start and end index.
- join() : It merges (concatenates) the sequence into a string.
- split() : It splits the string according to the passed delimiter string and returns the list of substrings.
- splitlines() : It splits the string at all newlines or the number of newlines and returns a list of each line with newlines removed.
- find() : It returns the index value of the string, where a given substring is found between the given start index and end index.
- rfind() : It works the same as the find() method but only searches from the backward in a string.
- index() : It works same like find() method only raises an exception if substring is not found in a string between given start and end index.
- rindex() : It works the same as the index() method but only searches from the backward in a string.
Related Articles
Python String – Mastering By Practical Examples (Comprehensive Guide)
Python Tutorials List:
- Python tutorials list : access all python tutorials.