Replace character in string python; Through this tutorial, i am going to show you how to replace occurrence characters/letters from string in python.
How to Replace Character in String in Python
Use the python replace() method returns a copy of the string where all occurrences of a substring is replaced with another substring.
The syntax of python 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: How to replace multiple character in string in python
See the following python program to replace multiple character in string using replace() method:
string = 'python is good programming language. Python is best programming language' '''occurences of 'python' is replaced''' print(string.replace('python', "The python"))
The python is good programming language. Python is best programming language
Example 2: How to replace first two characters of string in python
See the following python program to replace first two characters of string in python:
txt = "one one was a race horse, two two was one too." x = txt.replace("one", "three", 2) print(x)
three three was a race horse, two two was one too