Python String replace() Method

The replace() functions/method replaces all occurrences of a specified substring in a string and returns a new string without modifying the original string.

Let’s look at a simple example of replace() method.

Python

s = "Hello World! Hello Python!"

# Replace "Hello" with "Hi"
s1 = s.replace("Hello", "Hi")

print(s1)
Output

Hi World! Hi Python!

Explanation: Here, “Hello” is replaced by “Hi” throughout the string, resulting in “Hi World! Hi Python!“.

Note: Since replace() creates a new string, the original string remains unchanged.

Syntax of String replace() Method

string.replace(old, new, count)

Parameters

  • old: The substring we may be interested to replace.
  • new: The new substring that we may be interested to replace with old substring.
  • count (optional): Specifies the maximum number of replacements to perform. If omitted, all occurrences are replaced.

Return Type

  • Returns a new string with the specified replacements made. The original string remains unchanged since strings in Python are immutable.

Using replace() with Count Limit

By using the optional count parameter, we can limit the number of replacements made. This can be helpful when just a specific number of replacements are desired.

Python

s = "apple apple apple"

# Replace "apple" with "orange" just once
s1 = s.replace("apple", "orange", 1)

print(s1)
Output

orange apple apple

Explanation: replace() method just replaces the first instance of “apple” because we specified count=1.

Case Sensitivity in replace()

The replace() functions/method is case-sensitive, it treats uppercase and lowercase characters when distinct. If we may be interested to replace both cases then we have to use additional logic.

Python

s = "Hello, World! hello, world!"

# Replace just lowercase 'hello'
s1 = s.replace("hello", "hi")
print(s1)

# Replace just uppercase 'Hello'
s2 = s.replace("Hello", "Hi")
print(s2)
Output: text in bold will get updated

Hello, World! hi, world!
Hi, World! hello, world!

Explore More

Python 10 Programs for Beginners

Program 1:Write a program to create a 2D array using NumPy. Output: Program 2: Write a program to convert a python list to a NumPy array. Output: Program 3: Write a program to create matrix of 3×3 from 11 to 30. Output: Program 4: Write a program to create a data frame to store data of candidates who appeared in

Find index of first occurrence when an unsorted array is sorted

Find index of first occurrence when an unsorted an array is sorted Given an unsorted an array and a number x, find an index of first occurrence of x when

Find sum non repeating distinct elements array

Find sum of non-repeating (distinct) elements in an array Given an integer an array with repeated elements, the task is to find the sum of all distinct elements in the