Python String replace() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Python String replace() method

The replace() method in Python replaces a specified substring with another substring.

It’s not case sensitive.

Syntax of replace() method
string.replace(old_value, new_value, count)

old_value: The substring to be replaced(required)
new_value: The substring to replace with(required)
count: A number specifying the number of occurences 
       of old_value to replace. (Optional)
       If nothing is mentioned, all occurences are replaced.
Example 1

Code/Output

str1 = "Pylenin loves Python"
print(str1.replace("Python","Apples"))
>>> Pylenin loves Apples

# replacing a non-existing substring
str1 = "Pylenin loves Python"
print(str1.replace("mangoes","Apples"))
>>> Pylenin loves Python

# check for case sensitivity
str1 = "Pylenin loves Python"
print(str1.replace("python","Apples"))
>>> Pylenin loves Python
Example 2 - Changing multiple occurences of a substring

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin"
print(str1.replace("Python","Apples", 1))
>>> Pylenin loves Apples and Python loves Pylenin

As you see, only the first occurence of Python is changed to Apples.

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide