write a python program to do a case insensitive string replacement

Python program to case insensitive string replacement :

This article will show you how to do case insensitive string replacement in Python. The program will take the string and the sub-string to replace as inputs from the user. case-insensitive string replacement doesn’t consider any cases while doing the replacement. For example, if the string is World, worlD and WORLD both will match this string irrespective of the character cases.

We will take the help of regex module re to do the replacement.

re module :

re module is used for regular expression in python. We will use the sub method of this module. sub is used to replace substrings in a string. Below is the definition of the sub method :

re.sub(pattern, repl, str, count=0, flags=0)

It returns one new string by replacing all pattern in the string str by repl. If the pattern doesn’t match with any word, it returns the str unchanged. count is the number of matching words we want to replace. It starts the replacement from left side.

flags is optional but it is a important field in our case. We will pass re.IGNORECASE as flags, that will do the replacement case-insensitive.

Python Program :

Below is the python program to do case insensitive string replacement :

import re

given_text = 'Hello ! hello All ! HELLO everyone !'

new_text = re.sub('hello', 'Hi', given_text, flags=re.IGNORECASE)

print(new_text)

The above example will give the below output :

Hi ! Hi All ! Hi everyone !

Here, we have replaced the words Hello, hello and HELLO by Hi. If you remove the flags parameter, it will replace only the hello world.