How To Make Python Not Case Sensitive

Python is a case-sensitive language, which means that variables, function names, and other identifiers that are spelled the same but use different cases are treated as distinct entities. While this feature adds flexibility and precision to the language, it can sometimes be a source of confusion or frustration for developers who prefer case-insensitive code.

In this blog post, we’ll explore how to make Python not case sensitive by using a few simple techniques. These approaches can be employed in various situations where case sensitivity may not be desired, such as when working with user input, dictionary keys, or string comparisons.

Lowercasing Strings

One simple way to make Python not case sensitive is to convert all strings to lowercase (or uppercase) before performing any comparisons or operations on them. You can use the lower() method on a string to achieve this. Here’s an example:

text = "Hello, World!"
lowercase_text = text.lower()

print(lowercase_text)  # Output: "hello, world!"

With this technique, you can easily compare two strings without considering their case, like this:

string1 = "Python"
string2 = "python"

if string1.lower() == string2.lower():
    print("The strings are equal, ignoring case.")
    print("The strings are not equal.")

Case-Insensitive Dictionaries

If you need to store data in a dictionary with case-insensitive keys, you can use the collections.ChainMap class along with the lower() method we discussed earlier. Here’s an example of how to create a case-insensitive dictionary:

from collections import ChainMap

class CaseInsensitiveDict(ChainMap):
    def __getitem__(self, key):
        return super().__getitem__(key.lower())

    def __setitem__(self, key, value):
        super().__setitem__(key.lower(), value)

# Usage:
my_dict = CaseInsensitiveDict()

my_dict["Key1"] = "value1"
print(my_dict["key1"])  # Output: "value1"

Custom String Comparison Function

If you find yourself comparing strings frequently in your code, you might want to create a custom string comparison function that ignores case. Here’s an example of how you could do this:

def strings_equal_ignore_case(str1, str2):
    return str1.lower() == str2.lower()

# Usage:
string1 = "Hello"
string2 = "hello"

if strings_equal_ignore_case(string1, string2):
    print("The strings are equal, ignoring case.")
    print("The strings are not equal.")


In this blog post, we explored a few techniques to make Python not case sensitive, including converting strings to lowercase, creating case-insensitive dictionaries, and defining custom string comparison functions. While Python is inherently a case-sensitive language, these methods can help you work with case-insensitive data or develop more user-friendly applications.