Menu Close

Python String replace() Method

Python String replace

In this article, you will learn about the Python string replace() method. Python string replace() method is a very useful method to replace the old string with a new string.

In the previous tutorial, we have seen the Python string partition method to split the string for a specified value.

Python String replace() Method

Python replace() string method is used to replace the old string with a new string and return a new string.

Syntax

The syntax of replace function in Python is:-

string.replace(oldvalue, newvalue, count)

Parameter

The replace function in Python accept three parameters.

  • oldvalue:- An old string that will be replaced.
  • newvalue:- New string which will replace the old string.
  • count:- ( Optional ) A number specifying how many occurrences of the old value you want to replace.

Return Value

Python string replace method return new string.

Python string replace example:

Here we will take some examples to understand replace function in Python.

Example 1:

a = 'Python is Best Programming Language For Game Application.'
result = a.replace('Python', 'C++')
print(result)

Output

C++ is Best Programming Language For Game Application.

Example 2:

a = 'C++'
result = a.replace('C++','Python is the best language for Machine Learning.')
print(result)

Output

Python is the best language for Machine Learning.

Example 3

a = 'Python is a case-sensitive programming language. Python is used in various software domains. That\'s why Python is the most popular.'
result = a.replace('Python', 'C++', 2)
print(result)

Output

C++ is a case-sensitive programming language.C++ is used in various software domains. That's why Python is the most popular.

In above example, only two string replace with new string because we provide third parameter. Third parameter indicate how many only string should be replace.

Conclusion:

In this tutorial, you have learned the Python string replace method to replace the old string with a new string. This is the best string method to replace the old string with a new string.

I hope this tutorial will help you. If you like this article, please share it with your friends who want to learn Python programming.

String Methods


For More Information:- Click Here

Python String lstrip() Method
Python String rindex() Method

Related Posts