Python replace


You saw earlier that you can't replace a single letter in a Python string using index numbers. We tried to turn String into Strong:

myText = "String"
myText[3] = "o"

This got us an error. However, there is a Python function called replace(). Because strings are immutable, the trick is to create a new string and then use replace on the old one.

Let's see how it works.

Add the following variable to your code:

myOldText = "String"

Now set up a new variable and use the Python replace() function:

myNewText = myOldText.replace("i", "o")

Add a couple of print statements to see the difference between the two:


You should now see String and Strong in the output window.

The first thing you need for the replace function is your old text. This is usually inside of a variable. Next, use the replace function. Inside of the round brackets of replace, type the string you want to replace, then a comma. Next, type the text you want to replace the old text with. We just want the letter o in place of the letter i.

You can replace as many characters as you want, and not just the one character as we have done. You can even use variables instead of direct text in quotes. As long as those variables contain text, you're okay.

Something we've missed out of our replace function is the count. Try this. Change String to Stringing:

myOldText = "Stringing"
myNewText = myOldText.replace("i", "o")

Now you'll see Strongong printed to the output window. Every letter i has been replaced. But we'd just like the first occurrence of i to be replaced, not every occurrence.

To solve the problem, the replace() function comes with an optional third parameter called count. After a comma, you type a number. The number is how many occurrences of your old text you want to replace. Change your replace line to this:

myNewText = myOldText.replace("i", "o", 1)

Run your code again and you should see Stronging printed rather than Strongong. Python has only replaced 1 letter i, the first one.

If no occurrences of your old string are found, you get a copy of the old string.

In the next lesson, we'll have a look at the Python keyword in.

Python in >