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
828

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)
🌐
GitHub
github.com › dsindex › blog › wiki › [python]-string-compare-disregarding-white-space
[python] string compare disregarding white space
July 29, 2014 - 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
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
How to compare string and ignore white space and cases?
Exmple Input : var a = Mark N Lautz var b = Mark N Lautz It should return true since the same string the only difference it white spaces. Thanks. More on forum.uipath.com
🌐 forum.uipath.com
19
0
May 24, 2021
performance - Comparing strings, ignoring case, punctuation, and whitespace - Code Review Stack Exchange
Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 31, 2017
bash - How to do a string comparison ignore whitespace? - Unix & Linux Stack Exchange
How would you compare two strings but ignoring whitespaces? I am doing the following: if [ "$a" == "$b" ]; then echo ok fi But it doesn't seem to match. I've printed what "a" and "b" are and th... More on unix.stackexchange.com
🌐 unix.stackexchange.com
January 24, 2017
People also ask

Is Python string comparison case sensitive?
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.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › python › python compare strings (==, ignore case, substring, examples)
Python Compare Strings (==, Ignore Case, Substring, Examples) | ...
How do you compare strings ignoring case in Python?
Convert both strings to lowercase or use casefold before comparison. Example: `a.lower() == b.lower()` or `a.casefold() == b.casefold()` for better Unicode support.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › python › python compare strings (==, ignore case, substring, examples)
Python Compare Strings (==, Ignore Case, Substring, Examples) | ...
How do you check if a substring exists in a string in Python?
Use the `in` operator to check for substring presence. For example: `"hello" in "hello world"` returns True if the substring exists.
🌐
golinuxcloud.com
golinuxcloud.com › home › programming › python › python compare strings (==, ignore case, substring, examples)
Python Compare Strings (==, Ignore Case, Substring, Examples) | ...
🌐
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
12345 # Comparing international usernames regardless of letter case username_db = "straße" username_input = "STRASSE" print(username_db.casefold() == username_input.casefold()) # True → matches even with special characters ... Users often add spaces by accident. Remove leading and trailing whitespace before comparing. 12345 # Validating a user's role input from a form user_input = " admin " required_role = "ADMIN" print(user_input.strip().casefold() == required_role.casefold()) # True → matches after cleanup and case normalization
🌐
Miguendes
miguendes.me › python-compare-strings
How to Compare Two Strings in Python (in 8 Easy Ways)
July 2, 2022 - If that is the case, then str.strip is not enough. >>> s2 = ' Hey, I really like this post. ' >>> s1 = 'Hey, I really like this post.' >>> s1.strip() == s2.strip() False · The alternative then is to remove the duplicate whitespaces using a regular expression.
🌐
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.
Find elsewhere
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › python compare strings (==, ignore case, substring, examples)
Python Compare Strings (==, Ignore Case, Substring, Examples) | GoLinuxCloud
April 12, 2026 - Learn how to compare strings in Python with practical examples. This guide covers string equality, case-insensitive comparison, substring matching, lexicographic comparison, character-by-character comparison, and real-world use cases. Understand how Python handles string comparison, common ...
🌐
UiPath Community
forum.uipath.com › help › studio
How to compare string and ignore white space and cases? - Studio - UiPath Community Forum
May 24, 2021 - Exmple Input : var a = Mark N Lautz var b = Mark N Lautz It should return true since the same string the only difference it white spaces. Thanks.
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
  }    
}
🌐
Reddit
reddit.com › r/linux4noobs › bash scripting question if it's allowed: comparing strings, substring, ignore case/whitespace
r/linux4noobs on Reddit: bash scripting question if it's allowed: comparing strings, substring, ignore case/whitespace
November 11, 2022 -

Hi! mega mega noob, literally first day of bash and I am struggling any help would be appreciated!!

I need to compare two strings and find whether string A exists as a substring of string B. The comparison needs to ignore case and ignore whitespace.

String A is saved in a txt file (ex: test.txt).

String B is the output of a file that used some input, I have literally no clue in what format the output exists but this is the line that creates the variable (output should be the console output of a program that is run with the pre-set input):

java "$(find *.java | sed 's/\.java$//1')" < input > output

So I need to find whether the text in test.txt exists as a substring of the output string, ignoring case and ignoring all horizontal and vertical whitespace (not just edge whitespace).

I've tried varieties of diff, tr, and if statements using =~ and ** but nothing is working and I really don't know enough to troubleshoot...help?

🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-equals
How to Check if Two Strings Are Equal in Python (With Examples) | DigitalOcean
September 12, 2025 - Trailing or leading whitespace can lead to misleading results when comparing strings. To fix this, use the strip() method to remove any leading or trailing whitespace before comparing strings.
🌐
GitHub
github.com › xunit › xunit › issues › 2440
Add way to compare strings more fully ignoring whitespace. · Issue #2440 · xunit/xunit
December 13, 2021 - Currently, when comparing strings, options like ignoreLineEndingDifferences and ignoreWhiteSpaceDifferences require there be at least one instance of the various characters // Succeeds Assert.Equal(" ", " ", ignoreWhiteSpaceDifferences: ...
Author   xunit
🌐
H3manth
h3manth.com › content › comparing-strings-variable-white-spacing
Comparing Strings with variable white spacing | Experiments on GNU/Linux
April 12, 2012 - Comparing Strings with variable white spacing, is also one among the most common cases, below /me has tried to collect the most intuitive way of doing it in Ruby, Perl, Python and Javascript · Say we have two strings str1="hemanth is testing" and str2="hemanth is testing" with white spaces in consideration, these two strings are not equal, but logically handling the extra spaces would reveal that these strings are equal, which plays a very important role in fileds like : parsing, NPL, testing and so forth. On the other hand, if we try to compare strings ignoring cases, we will end up with wrong results, say for example comparing two strings like "a book" and "ab o ok" ignoring spaces would be the same, but they are in real not!
🌐
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
def validate_command(user_input, valid_commands): """ Validate if the user input matches any of the valid commands, ignoring case differences. Returns the standardized command if valid, None otherwise. """ ## Convert user input to lowercase for comparison user_input_lower = user_input.strip().lower() for cmd in valid_commands: if user_input_lower == cmd.lower(): ## Return the standard casing of the command return cmd ## No match found return None ## List of valid commands with standard casing VALID_COMMANDS = [ "Help", "Exit", "List", "Save", "Delete" ] ## Test with various inputs test_inputs
🌐
Reddit
reddit.com › r/learnpython › how to compare two strings that look the same but aren't
r/learnpython on Reddit: How to compare two strings that look the same but aren't
August 10, 2020 - string1_no_whitespace = string1.replace(" ", "") string2_no_whitespace = string2.replace(" ", "") are_strings_equal = (string1_no_whitespace == string2_no_whitespace) ... i would be curious if removing non-ascii characters or doing some unicode conversion on the text you are scraping would be of any benefit? https://repl.it/@nickangtc/python-strip-non-ascii-characters-from-string#main.py
🌐
Finxter
blog.finxter.com › how-to-ignore-case-in-strings
How to Ignore Case in Python Strings – Be on the Right Side of Change
August 19, 2022 - In this article, you’ll learn how to ignore (upper/lower/title) case characters when dealing with Strings in Python · The main reason for ignoring the case of a String is to perform accurate String comparisons or to return accurate search results
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-comparison
Python Compare Strings: Methods, Operators & Best Practices | DigitalOcean
June 15, 2026 - When comparing strings, you need ... practices keep string comparisons accurate and efficient. To compare strings while ignoring upper and lower case, use the .lower() method to convert both strings to lowercase before comparing them....