Python string data type provides the
replace() method in order to replace or change specified characters with the provided characters. The new or replaced string is returned by the replace() method.
String replace() Method Syntax
Python string replace() method has the following syntax where up to 3 parameters can be provided but in general 2 parameter version is the most popular. The replace() method is a built-in method where there is no need to import any module and provided string types of objects.
STRING.replace( OLDVALUE , NEWVALUE , COUNT)
- STRING is the string where we will replace the OLDVALUE with the NEWVALUE. The replaced version of the string will be returned by the replace() method.
- OLDVALUE is the value that currently exists in the STRING that can be changed. OLDVALUE is required.
- NEWVALUE is the value that will be set as the new value and replace with the OLDVALUE. NEWVALUE is required.
- COUNT is an optional parameter where how many times the replacement operation will be taken. By default, if the COUNT is not provided there is no limit.
String replace() Method Example
Now make some examples about the replace() method. We wil
s1 = "This is a text where the replace method will be called" s2 = "one plus one is not equal to the one" print( s1.replace( "e" , "3" ) ) print( s2.replace( "one" , "two" ) ) print( s2.replace( "one" , "two" , 1 ) ) print( s1.replace( "one" , "two" , 2 ) )
Using Multiple/Chained replace Method
In some cases you may need to replace multiple characters in a fast and easy way. You may use the replace() method multiple times in multiple lines but you can also use the replace() method in a single line in a chained way. In the following example we will call the replace method mulitiple times in a string.
s = "one plus one is not equal to the one" print( s2.replace( "one" , "two" ).replace( "two" , "three" ) )