Python Replace String with Case Insensitive for Beginners – Python Tutorial

By | August 29, 2019

In python, to replace an old string with a new string, we can use string.replace(old, new) function. However, this function is case sensitive. In this tutorial, we will introduce a way to replace string with case insensitive.

string.replace() is case sensitive

s='https://www.tutorialexample.com'
s = s.replace("Https", 'http')
print(s)

The result is: https://www.tutorialexample.com

From result, we can find string.replace() is case sensitive.

How to replace string with case insensitive?

We can use python regression expression to do it.

Here is an example:

import re
def replace(old, new, str, caseinsentive = False):
    if caseinsentive:
        return str.replace(old, new)
    else:
        return re.sub(re.escape(old), new, str, flags=re.IGNORECASE)

In this function, if caseinsentive = False, this function will replace old string with new string case-insensitively.

How to use?

s='https://www.tutorialexample.com'
s = replace("Https", 'http', s)
print(s)

The result is:

https://www.tutorialexample.com

From the result, we can find our function works.

Leave a Reply

Your email address will not be published. Required fields are marked *