Home » Programming » Python » Python String Replace

Python String replace Method [With Examples]

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"

Check out our other articles on Python functions!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment