Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

As of Python 3.3, casefold() is a better alternative:

string1 = 'Hello'
string2 = 'hello'

if string1.casefold() == string2.casefold():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

If you want a more comprehensive solution that handles more complex unicode comparisons, see other answers.

Answer from Harley Holcombe on Stack Overflow
Top answer
1 of 15
827

Assuming ASCII strings:

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

As of Python 3.3, casefold() is a better alternative:

string1 = 'Hello'
string2 = 'hello'

if string1.casefold() == string2.casefold():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

If you want a more comprehensive solution that handles more complex unicode comparisons, see other answers.

2 of 15
740

Comparing strings in a case insensitive way seems trivial, but it's not. I will be using Python 3, since Python 2 is underdeveloped here.

The first thing to note is that case-removing conversions in Unicode aren't trivial. There is text for which text.lower() != text.upper().lower(), such as "ß":

>>> "ß".lower()
'ß'
>>> "ß".upper().lower()
'ss'

But let's say you wanted to caselessly compare "BUSSE" and "Buße". Heck, you probably also want to compare "BUSSE" and "BUẞE" equal - that's the newer capital form. The recommended way is to use casefold:

str.casefold()

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. [...]

Do not just use lower. If casefold is not available, doing .upper().lower() helps (but only somewhat).

Then you should consider accents. If your font renderer is good, you probably think "ê" == "ê" - but it doesn't:

>>> "ê" == "ê"
False

This is because the accent on the latter is a combining character.

>>> import unicodedata
>>> [unicodedata.name(char) for char in "ê"]
['LATIN SMALL LETTER E WITH CIRCUMFLEX']
>>> [unicodedata.name(char) for char in "ê"]
['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT']

The simplest way to deal with this is unicodedata.normalize. You probably want to use NFKD normalization, but feel free to check the documentation. Then one does

>>> unicodedata.normalize("NFKD", "ê") == unicodedata.normalize("NFKD", "ê")
True

To finish up, here this is expressed in functions:

import unicodedata

def normalize_caseless(text):
    return unicodedata.normalize("NFKD", text.casefold())

def caseless_equal(left, right):
    return normalize_caseless(left) == normalize_caseless(right)
🌐
GeeksforGeeks
geeksforgeeks.org › python › case-insensitive-string-comparison-in-python
Case-insensitive string comparison in Python - GeeksforGeeks
July 15, 2025 - It converts all strings, checks uniqueness using a set and prints "equal" if all are identical otherwise, "unequal". re.match() checks if a string matches a pattern from the start and with the re.IGNORECASE flag, it ignores case differences.
Discussions

Python : How to compare strings and ignore white space and special characters - Stack Overflow
I want to compare two strings such that the comparison should ignore differences in the special characters. That is, Hai, this is a test Should match with Hai ! this is a test "or" Hai this i... More on stackoverflow.com
🌐 stackoverflow.com
performance - Comparing strings, ignoring case, punctuation, and whitespace - Code Review Stack Exchange
I have built a search function that will compare strings regardless of punctuation and whitespace. It is case insensitive. More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 31, 2017
How can I perform case-insensitive string comparison in Python? - Python - Data Science Dojo Discussions
I have two strings, and I want to compare them without considering their cases. How can I achieve this in Python? I have tried using the == operator, but it considers the case while comparing the strings. Here’s what I have done so far: This code snippet uses the lower() method to convert ... More on discuss.datasciencedojo.com
🌐 discuss.datasciencedojo.com
1
0
April 26, 2023
Ignore punctuation and case when comparing two strings in Python - Stack Overflow
I have a two dimensional array called "beats" with a bunch of data. In the second column of the array, there is a list of words in alphabetical order. I also have a sentence called "words" which was More on stackoverflow.com
🌐 stackoverflow.com
🌐
LabEx
labex.io › tutorials › python-how-to-compare-two-python-strings-for-equality-in-a-case-insensitive-manner-395043
How to compare two Python strings for equality in a case-insensitive manner? | LabEx
For more advanced scenarios, you can use regular expressions with the re module and the IGNORECASE flag: Add the following code to your case_insensitive.py file: ## Case-insensitive comparison using regular expressions import re text = "Python is a great programming language." pattern1 = "python" ## Check if 'python' exists in the text (case-insensitive) match = re.search(pattern1, text, re.IGNORECASE) print(f"Found '{pattern1}' in text?
Top answer
1 of 2
2

You might want to create a combined CharacterSet of punctuation and whitespace first and then apply this set using a single operation. This should speed things up. Please have a look at this code snippet:

let punctuation = CharacterSet.punctuationCharacters
let whitespace = CharacterSet.whitespaces
let unwanted = punctuation.union(whitespace)
let components = filterString.components(separatedBy: unwanted).joined(" ")
let filterStringContainsSearchText = components.contains(searchText)
2 of 2
1

Optimizing your search will require that you don't repeat costly operations on every item if they can be performed once beforehand.

It would also help to avoid the overhead of special character processing if the search text doesn't justify it (e.g if it has no spaces or special characters itself).

Finally, procedural code (for loops) are optimized more efficiently by the compiler than their "functional" equivalent (.filter / .map) so the traversal of songs should be performed in a loop instead of a .filter()

I would suggest extending the MPMediaQuery class to allow it to provide a filtered list of songs in the most optimal way possible. This has some reuse value and will keep your main logic more readable and maintainable.

On the other hand, if the MPMediaQuery goes back to storage every time, it will be more efficient to create a simple function that takes the array of songs as a parameter.

For example:

extension MPMediaQuery
{
   static func songsMatching(_ searchText:String) -> [MPMediaItem]
   {
      // Common function to turn special characters into spaces
      // will have a certain amount of overhead so we will try
      // to avoid using it if possible...
      func normalizedText(_ text:String) -> String
      {
         let chars = text.unicodeScalars.enumerated()
                         .map ({ 
                                   CharacterSet.punctuationCharacters.contains($1)
                                || CharacterSet.whitespaces.contains($1) 
                                   ? " " : Character($1)
                              })
         return String(chars)
      }

      // Search string should only be prepared once
      // This means that the whole filtering operation needs to be
      // included in the optimization.
      let searchString  = searchText.lowercased()      
      let cleanedString = normalizedText(searchString)

      // based on search string content, we can forgo complex comparisons
      // We only need to manage special characters if the search text
      // contains any.
      // If the search text doesn't contain spaces or special characters
      // then removing them from the titles is unnecessary
      let simpleFilter = !cleanedString.contains(" ")

      // The Swift optimizer is much more efficient compiling procedural
      // code (As opposed to the functional style .filter{} and such)
      // This can give a 20x speed boost in some cases.
      var result:[MPMediaItem] = []
      for song in songs().items ?? []
      {
         guard let title = song.title?.lowercased()
         else { continue }

         if simpleFilter
         { 
            if title.contains(searchString)
            { result.append(song) }
         }
         else
         {
            if normalizedText(title).contains(searchString)
            { result.append(song) }
         }
      }

      return result
  }    
}
🌐
GitHub
github.com › dsindex › blog › wiki › [python]-string-compare-disregarding-white-space
[python] string compare disregarding white space
July 29, 2014 - 흥미로운 내용이다. python에서 문자열을 비교할때, whitespace를 무시하고 비교하는 방법 · import string NULL = string.maketrans("","") WHITE = string.whitespace WHITE_MAP = dict.fromkeys(ord(c) for c in WHITE) def compare(a,b): """ Compare two base strings, disregarding whitespace """ # unicode의 경우 if isinstance(a, unicode): astrip = a.translate(WHITE_MAP) # unicode가 아닌 경우 else: astrip = a.translate(NULL, WHITE) if isinstance(b, unicode): bstrip = b.translate(WHITE_MAP) else: bstrip = b.translate(NULL, WHITE) return astrip == bstrip
Author   dsindex
Find elsewhere
🌐
Codefinity
codefinity.com › courses › v2 › 0c5b58ba-087d-4eec-9e76-db6dab16372e › e5e45c4a-f463-4dfe-90f7-74e74489f315 › e2e6f78c-f518-4a65-a1af-9f3aac76da93
Learn Comparing Strings | Cross-Type Interactions
A simple and reliable recipe is to trim whitespace and standardize case before any equality or prefix/suffix checks. By default, "Apple" == "apple" is False. To ignore case, normalize both sides.
🌐
Netalith
netalith.com › blogs › tutorial › python-compare-strings-methods-best-practices
Python String Comparison: Compare Strings Effectively | Netalith
February 24, 2026 - Simple preprocessing can help: def normalize_for_compare(s): # trim, collapse spaces, fold case, and normalize Unicode s = ' '.join(s.split()) # remove extra whitespace s = unicodedata.normalize('NFKD', s) s = ''.join(ch for ch in s if not ...
🌐
Unstop
unstop.com › home › blog › 12 ways to compare strings in python with examples
12 Ways To Compare Strings In Python With Examples
March 18, 2024 - We can use the Python string replace() method to replace the white spaces with no space. By eliminating whitespace, the comparison focuses solely on the content of the strings, making it useful for scenarios like comparing user inputs or handling ...
🌐
Miguendes
miguendes.me › python-compare-strings
How to Compare Two Strings in Python (in 8 Easy Ways)
July 2, 2022 - The solution here is to strip the whitespace from the string the user enters and then compare it. You can do it to whatever input source you don't trust. In this guide, we saw 8 different ways of comparing strings in Python and two most common ...
🌐
Data Science Dojo
discuss.datasciencedojo.com › python
How can I perform case-insensitive string comparison in Python? - Python - Data Science Dojo Discussions
April 26, 2023 - I have tried using the == operator, but it considers the case while comparing the strings. Here’s what I have done so far: This code snippet uses the lower() method to convert both strings to lowercase before comparing them using the == operator.
🌐
TutorialsPoint
tutorialspoint.com › article › python-program-to-compare-two-strings-by-ignoring-case
Python Program to compare two strings by ignoring case
March 27, 2026 - The casefold() method is more aggressive than lower() and handles special Unicode characters better ? string1 = "Straße" # German word with ß string2 = "STRASSE" if string1.casefold() == string2.casefold(): print("The strings are equal, ignoring ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-equals
How to Check if Two Strings Are Equal in Python (With Examples) | DigitalOcean
September 12, 2025 - You can do a case-insensitive string comparison in Python by converting both strings to lowercase or uppercase using the lower() or upper() method, respectively. ... Case sensitivity: Strings are case sensitive, so ‘Hello’ and ‘hello’ are not equal. Leading or trailing whitespace: Strings ...
🌐
TutorialsPoint
tutorialspoint.com › article › how-do-i-do-a-case-insensitive-string-comparison-in-python
How do I do a case-insensitive string comparison in Python?
March 24, 2026 - In some tasks, such as searching user input, comparing filenames, or processing natural language, it's important to compare strings without considering case differences. To perform string comparison in Python, we have several built-in methods such as lower(), upper(), and casefold(), which help us to normalize the casing of strings before comparing them.
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › python compare strings (==, ignore case, substring, examples)
Python Compare Strings (==, Ignore Case, Substring, Examples) | GoLinuxCloud
April 12, 2026 - Yes, Python string comparison is case sensitive by default. For example, "Hello" and "hello" are considered different. To ignore case, use lower() or casefold() before comparing.
🌐
iO Flood
ioflood.com › blog › using-python-to-compare-strings-methods-and-tips
Python String Comparison Methods | Quick User Guide
August 13, 2024 - Because the strings are identical, they are stored in the same memory location and you just have to check that two strings point to the same memory. Case insensitive comparisons require additional processing. What if you want to disregard case when comparing strings? Python offers several methods for this purpose, including ‘lower()’, ‘upper()’, and ‘casefold()’.
🌐
Sling Academy
slingacademy.com › article › python-ways-to-compare-2-strings-ignoring-case-sensitivity
Python: 3 ways to compare 2 strings ignoring case sensitivity - Sling Academy
It ensures that strings with different case variations are considered equivalent, enhancing flexibility and user-friendliness · This concise code-centric article will walk you through a few different ways to compare two strings ignoring case sensitivity in Python. ... The casefold() method is ...