Replace All Occurrences of a Python Substring with a New String?


In this article, we will implement various example to replace all occurrences of a substring with a new string. Let’s say we have the following string −

Hi, How are you? How have you been?

We have to replace all occurrences of substring “How “ with “Demo”. Therefore, the output should be 

Hi, Demo are you? Demo have you been?

Let us now see some examples 

Replace All Occurrences of a Python Substring with a New String using replace()

Example

In this example, we will use the replace() method to replace all occurrences of a Python Substring with a New String −

# String myStr = "Hi, How are you? How have you been?" # Display the String print("String = " + myStr) # Replacing and returning a new string strRes = myStr.replace("How", "Demo") # Displaying the Result print("Result = " + strRes)

Output

String = Hi, How are you? How have you been?
Result = Hi, Demo are you? Demo have you been?

Replace Occurrences of Substrings with a New String using Regex sub()

Let’s say you want to replace distinct substrings. For that, we can use Regex. In the below example, we are replace distinct substrings “What” and “How” with “Demo”.

First, Install the re module to work with Regex in Python −

pip install re

Then, import the re module 

import re

Following is the complete code 

import re # String myStr = "Hi, How are you? What are you doing here?" # Display the String print("String = " + myStr) # Replacing and returning a new string strRes = re.sub(r'(How|What)', 'Demo', myStr) # Displaying the Result print("Result = " + strRes)

Output

String = Hi, How are you? What are you doing here?
Result = Hi, Demo are you? Demo are you doing here?

Replace Occurrences of Python Substrings with New Strings using Pattern Objects

Example

Following is the code 

import re # String myStr1 = "Hi, How are you?" myStr2 = "What are you doing here?" # Display the String print("String1 = " + myStr1) print("String2 = " + myStr2) # Replacing with Pattern Objects pattern = re.compile(r'(How|What)') strRes1 = pattern.sub("Demo", myStr1) strRes2 = pattern.sub("Sample", myStr2) # Displaying the Result print("\nResult (string1) = " + strRes1) print("Result (string2) = " + strRes2)

Output

String1 = Hi, How are you?
String2 = What are you doing here?
Result (string1) = Hi, Demo are you?
Result (string2) = Sample are you doing here?

Updated on: 15-Sep-2022

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements