w3resource logo
Python Exercises

Python: Do a case-insensitive string replacement

Python Regular Expression: Exercise-44 with Solution

Write a Python program to do a case-insensitive string replacement.

Sample Solution:-

Python Code:

import re
text = "PHP Exercises"
print("Original Text: ",text)
redata = re.compile(re.escape('php'), re.IGNORECASE)
new_text = redata.sub('Python', 'PHP Exercises')
print("Using 'php' replace PHP") 
print("New Text: ",new_text)

Sample Output:

Original Text:  PHP Exercises                                                                                 
Using 'php' replace PHP                                                                                       
New Text:  Python Exercises 

Python Code Editor:

import re
text = "PHP Exercises"
print("Original Text: ",text)
redata = re.compile(re.escape('php'), re.IGNORECASE)
new_text = redata.sub('Python', 'PHP Exercises')
print("Using 'php' replace PHP") 
print("New Text: ",new_text)

Improve this sample solution and post your code through Disqus