This article shows you how to use the string.replace() method in Python to replace elements in a string of characters and includes useful examples.
Python String replace Syntax
The replace() function can be called on existing string variables like so:
string.replace(find, new, count)
Where:
- string is the existing string variable
- find is the string your want found and replaced
- new is the text you want to replace the found text
- count is the number of instances of the found text you want to be replaced, counted from the beginning of the string being searched
Examples
Replacing All Occurrences
myText = "Cars are fast!" newText = myText.replace("Cars", "Rockets") print(newText) # Will return "Rockets are fast!"
Replacing Specified Number of Occurrences
This example will replace the first 2 occurrences of red:
myText = "red green red red green red" newText = myText.replace("red", "blue", 2) print(newText) # Will return "blue green blue red green red"
Removing Values
Pass an empty string as the second parameter to remove found values:
myText = "red green red red green red" newText = myText.replace("red", "", 2) print(newText) # Will return " green red green red"