Replace a character in string python; In this tutorial, you will learn how to replace a character in a string at index and without index in python
As well as, you will learn in detail about python string replace() methods syntax, parameters and return value etc.
How to replace a character in a string in python
The python replace() method returns a copy of the string where all occurrences of a substring are replaced with another substring.
The syntax of replace() is:
str.replace(old, new [, count])
parameters of replace() method
The replace() method can take maximum of three parameters:
- 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
If count is not specified, replace() method replaces all occurrences of the old substring with the new substring.
Return Value from replace()
The replace() method returns a copy of the string where old substring is replaced with the new substring. The original string is unchanged.
If the old substring is not found, it returns the copy of the original string.
Example 1: python replace multiple characters in string
string = 'python is good programming language. Python is best programming language'
'''occurences of 'python' is replaced'''
print(string.replace('python', "The python"))
Output
The python is good programming language. Python is best programming language
Example 2: Replace the two first occurrence of the string in python
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)
Output
three three was a race horse, two two was one too
Recommended Python Tutorials