How to use string.replace() in python

By Admin

How to use .replace() in python

April 2nd 5:59PM • 3 min read

In this Article You will:

How .replace() works

The .replace() function in python replaces all occurances of a string with another string.

Syntax

The .replace() function is used like this:


string.replace(target,newstring [, count])
                        
The string contains the text/phrase you want to replace, and the target is the text/phrase you want to replace with something else, and the newstring is the new text you want to replace it with. The optional count parameter specifies how many occurances of target you want to replace with newstring

Demonstration

For example, if we wanted to replace all of the "a"s in "ahahahaha" with "bah"s, we would use the following code below:


#define the string we want to replace
string = "ahahahaha"
string = string.replace("a","bah")
print(str)
                        
This would output:
"bahhbahhbahhbahhbah"

Note: that the string.replace() function returns a modified, new string instead of changing the value of the original string.