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 = s.replace("Https", 'http')

The result is:

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)
        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 = replace("Https", 'http', s)

The result is:

From the result, we can find our function works.

Leave a Reply

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