Simply call lower to make the string lowercase before calling endswith:

ext = (".dae", ".xml", ".blend", ".bvh", ".3ds", ".ase",
           ".obj", ".ply", ".dxf", ".ifc", ".nff", ".smd",
           ".vta", ".mdl", ".md2", ".md3"
           ".pk3", ".mdc", ".x"
           ".q3o", ".q3s", ".raw"
           ".ac", ".dxf", ".irrmesh"
           ".irr", ".off", ".ter"
           ".mdl", ".hmp", ".mesh.xml"
           ".skeleton.xml", ".material", ".ms3dv"
           ".lwo", ".lws", ".lxo"
           ".csm", ".cob", ".scn"
           ".xgl", ".zgl")
for folder, subfolders, filename in os.walk(directory):
    if any([filename.lower().endswith(tuple(ext)) for filename in filenames]):
Answer from javidcf on Stack Overflow
Top answer
1 of 2
55

Simply call lower to make the string lowercase before calling endswith:

ext = (".dae", ".xml", ".blend", ".bvh", ".3ds", ".ase",
           ".obj", ".ply", ".dxf", ".ifc", ".nff", ".smd",
           ".vta", ".mdl", ".md2", ".md3"
           ".pk3", ".mdc", ".x"
           ".q3o", ".q3s", ".raw"
           ".ac", ".dxf", ".irrmesh"
           ".irr", ".off", ".ter"
           ".mdl", ".hmp", ".mesh.xml"
           ".skeleton.xml", ".material", ".ms3dv"
           ".lwo", ".lws", ".lxo"
           ".csm", ".cob", ".scn"
           ".xgl", ".zgl")
for folder, subfolders, filename in os.walk(directory):
    if any([filename.lower().endswith(tuple(ext)) for filename in filenames]):
2 of 2
2

This is a really old answer but since Python 3.3, there exists the casefold() method which is more aggressive than lower() and is the more natural caseless string matching. So something like the following is an option:

filename.casefold().endswith(ext)

On a tangential note, any() short-circuits, meaning it stops at the first True, so it is much faster if any() is called on a generator expression instead of a list (especially if the matching string is towards the beginning of a long list) because with genexpr, we can stop the endswith check right away while with list, we have to perform the endswith check for every string before the any() evaluation.

So instead of

any([filename.lower().endswith(ext) for filename in filenames])
#   ^                                                        ^  <--- list

use

any(filename.lower().endswith(ext) for filename in filenames)
#  ^                                                        ^   <--- genexpr

Finally, since this question is tagged regex, here's a regex solution as well. Simply compile a pattern that ignores case and search whether the pattern matches.

import re
pat = re.compile(fr"({'|'.join(re.escape(e) for e in ext)})$", re.I)
for folder, subfolders, filenames in os.walk('.'):
    if any(pat.search(filename) for filename in filenames):
        # do something
🌐
Codecademy
codecademy.com › docs › python › strings › .endswith()
Python | Strings | .endswith() | Codecademy
April 21, 2025 - Yes, .endswith() is case-sensitive. Yes. Any string ends with an empty string, so calling .endswith("") on any string will return True. ... Looking for an introduction to the theory behind programming?
🌐
Medium
medium.com › @heyamit10 › understanding-pandas-endswith-8569d0441acc
Understanding pandas endswith. The biggest lie in data science? That… | by Hey Amit | Medium
April 12, 2025 - Is pandas endswith case-sensitive? Yes, the endswith method is case-sensitive. If you need a case-insensitive check, consider normalizing the string data using .str.lower() before using endswith.
🌐
Dive into Python
diveintopython.org › home › functions & methods › string methods › endswith()
endswith() in Python - String Methods with Examples
The endswith() method is case sensitive by default, but you can use case-insensitive comparison by converting the string to lowercase. text = 'Python Programming' print(text.lower().endswith('programming')) capitalize() casefold() center() count() encode() expandtabs() find() format() format_map() ...
🌐
Scaler
scaler.com › home › topics › endswith() python
endswith() python | endswith() Function in Python - Scaler Topics
March 30, 2022 - If we have passed a tuple of strings, then if any of the elements of the tuple matches the string, then also the endswith() will return True. Note: Case-sensitive means if the suffix content is in lower-case, and the string content is upper-case, then the method endswith() will also return False.
🌐
datagy
datagy.io › home › python posts › python strings › python string endswith: check if string ends with substring
Python String endswith: Check if String Ends With Substring • datagy
July 25, 2023 - In the code block above, we first use the .lower() method to represent the string in lowercase. Then, we can use the .endswith() method to check if a string ends with a pattern using case insensitivity. In this final section, you’ll learn how to use the Python endswith() method to check whether or not a string doesn’t end with a given string.
🌐
LabEx
labex.io › tutorials › python-how-to-check-if-a-string-ends-with-a-suffix-in-python-559571
How to Check If a String Ends with a Suffix in Python | LabEx
This demonstrates that the endswith() method is case-sensitive. To perform a case-insensitive check, you can convert the string to lowercase using the lower() method before using endswith().
Top answer
1 of 6
17

What about using python's builtin str.endswith() method?

def end_other(a, b):
    a_lower = a.lower()
    b_lower = b.lower()
    return a_lower.endswith(b_lower) or b_lower.endswith(a_lower)
2 of 6
7

I think this is what you were actually trying to do:

def end_other ( a, b ):
    a = a.lower()
    b = b.lower()
    if a == b:
        return True
    elif len( a ) > len( b ):
        return b == a[-len( b ):]
    else:
        return a == b[-len( a ):]

You had a couple of mistakes in your solution:

  • s1[-len(s2)] or generally s1[x] just gets a single character. So if anything, you are just comparing a single character, but not an actual sequence of characters. You splice a sequence out of a string by s[x:y] (see the manual).
  • s2[-len(s2)], even with the colon as explained above, doesn't make much sense. You are accessing s2 using its own length. But as s2 is already the smaller string, you can compare it as a whole.
  • When one of your outer ifs matches a situation, there is no way any other of the outer situations can follow. For example if a is longer than b, there is no way that a will be shorter or of the same length as b later on. As such you should make your if structure support that. Instead of if ... if ... if ... else make a chain: if ... elif ... elif ... else. Then one automatically knows that only one of those cases can apply.
  • When you do that, you can also leave off the last if expression. Because when neither x < y nor y < x equals to true, then x is equal to y.
  • You also need to change the way you return from within the function. As of now you have a conditional exit within each of your outer if cases. Now if the first if case applies (i.e. s1 is longer than s2) and the inner if does not apply (s1 does not end with s2), then you already know that the function should return False. Because there is no way that any other condition later in the code says otherwise, so you should return False immediately there (especially when there is other code that might execute later). And when you have if x: return True else: return False then you can just return x.
  • s1[-len(s1)]==s2[-len(s2)]: As other as already said you will have a problem when s1 and s2 are empty strings. len( "" ) = 0 and if both strings are empty, then both lengths are identical. And then your code tries to use an index range on an empty string, which will always fail (as there is not a single character). Instead, when you already know that two strings are of the same size, just compare both as a whole. This also helps against empty strings.

Anyway, if you didn't need to implement it on your own, you should really use str.endswith instead.

Find elsewhere
🌐
Data Science Parichay
datascienceparichay.com › home › blog › python string endswith – with examples
Python String Endswith - With Examples - Data Science Parichay
October 4, 2020 - Then, we check for the same suffix but with all characters as uppercase, 'TO CODE' which returns False, this shows that the endswith() function also takes into account the case of the strings. Finally, we check for the suffix 'to' which rightfully returns False. Example 2: Specifying the start and end parameters in the python string endswith() function.
🌐
AskPython
askpython.com › home › python string endswith() function
Python String endswith() function - AskPython
August 6, 2022 - str = 'Engineering is an interesting discipline' print(str.endswith('discipline', 11, len(str))) # True print(str.endswith('Engineering', 0, 11)) # True print(str.endswith('Python', 8)) # False
🌐
GeeksforGeeks
geeksforgeeks.org › case-insensitive-string-comparison-in-python
Case-insensitive string comparison in Python - GeeksforGeeks
April 22, 2025 - We are given a string and our task is to replace a specific word in it, ignoring the case of the letters. This means if we want to replace the word "best" with "good", then all variations like "BeSt", "BEST", or "Best" should also be replaced. For example, if the input is "gfg is BeSt", then the out ... Sometimes, while working with Python strings, we might have a problem in which we have list of strings and we wish to convert them into specified cases.
🌐
Django
code.djangoproject.com › ticket › 507
#507 (Make startswith and endswith case-sensitive in MySQL) – Django
If that doesn't work, how about adding a mechanism to the database layer where a Python function can be defined to perform further processing on a database result set before handing it back? The MySQL backend could then define a function for startswith and endswith that runs a normal case-insesitive search and then filters the results in Python code to find only case-sensitive matches.
🌐
ActiveState
code.activestate.com › recipes › 194371-case-insensitive-strings
Case Insensitive Strings « Python recipes « ActiveState Code
April 16, 2003 - It is quite possible in python to compare strings against integers or other non strings. So in __cmp__ and __eq__ I have added a try:except block around the current line, and in the except part put the same line but without the call to lower() (as it is this that raises the exception). e.g. def __cmp__(self, other): try: return cmp(self.__lowerCaseMe, other.lower()) except: return cmp(self.__lowerCaseMe, other) ... Terrible idea. Use a case-insensitive dictionary instead.
🌐
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?
June 10, 2025 - The casefold() method in Python is similar to the lower() method, but the difference is caseless matching, which is useful for comparing strings containing special characters or Unicode. This is recommended when working with Unicode data. str1 = "Straße" str2 = "strasse" if str1.casefold() == str2.casefold(): print("The strings are equal (case-insensitive with casefold)") else: print("The strings are not equal")
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › python startswith()
Python startswith(): Check String Prefix, Ignore Case, and Tuple Examples
June 23, 2026 - Use lower() or casefold() on both the string and prefix for case-insensitive checks. Pass a tuple to check multiple prefixes. Use start and end when you need to test a specific range.
🌐
Squash
squash.io › string-comparison-in-python-best-practices-and-techniques
String Comparison in Python: Best Practices and Techniques
May 21, 2024 - If you want to perform case-insensitive string comparison, you can convert the strings to lowercase or uppercase using the lower() or upper() string methods before performing the comparison.
🌐
Esdiscuss
esdiscuss.org › topic › case-insensitive-string-startswith-contains-endswith-replaceall-method
Case insensitive String startsWith, contains, endsWith, replaceAll method
February 18, 2013 - On Saturday, February 16, 2013, David Bruant wrote: > Le 17/02/2013 00:58, Biju a écrit : > >> In most time when user want to search something in a text, he/she >> wants to do a case insensitive search. >> For example to filter items displayed in list on a page. >> Also on other applications, say any word processor, or in page search >> in Firefox, IE, Chrome etc. >> >> So can we make the default behavior of new methods String.startsWith, >> String.contains, String.endsWith case insensitive?
🌐
Codecademy
codecademy.com › docs › python › strings › .startswith()
Python | Strings | .startswith() | Codecademy
April 17, 2025 - The following codebyte example ... whereas .endswith() checks if a given string ends with a specific value. Yes, .startswith() is case-sensitive....