Python Replace Character in String

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"))

Output

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)

Output

 three three was a race horse, two two was one too

Recommended Python Tutorials

Recommended:-Python Lists
Recommended:-Python Strings

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *