Python String replace Syntax
The replace() function can be called on existing string variables like so:
string.replace(find, new, count)
- 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
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"
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"