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?
🌐
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 - 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 ...
🌐
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.
🌐
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.
🌐
DataWider
datawider.com › articles › python case insensitive string comparison: every method you need to know
Python Case Insensitive String Comparison: Every Method You Need to Know
May 7, 2026 - Python’s built-in .startswith() and .endswith() are case-sensitive. To make them case-insensitive: ... Convert the string before calling the method.
🌐
AskPython
askpython.com › python › string › python-string-endswith-function
Python String endswith() function - AskPython
August 6, 2022 - str = 'C++ Java Python' print(str.endswith(('Perl', 'Python'))) # True print(str.endswith(('Java', 'Python'), 3, 8)) # True · Python String endswith() function is a utility to check if the string ends with the given suffix or not.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › case-insensitive-string-comparison-in-python
Case-insensitive string comparison in Python - GeeksforGeeks
April 22, 2025 - Explanation: This code uses casefold() for accurate case-insensitive comparison, especially with international characters. It converts all strings, checks uniqueness using a set and prints "equal" if all are identical otherwise, "unequal". ...
🌐
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.
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.

🌐
Esdiscuss
esdiscuss.org › topic › case-insensitive-string-startswith-contains-endswith-replaceall-method
Case insensitive String startsWith, contains, endsWith, replaceAll method
February 18, 2013 - And sometimes, case-sensitive is what you want. I agree, that is why I mentioned to add matchCase parameter. or have startsWithI, containsI, endsWithI instead
🌐
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().
🌐
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")
Top answer
1 of 7
70

You could use a regular expression as follows:

In [33]: bool(re.match('he', 'Hello', re.I))
Out[33]: True 

In [34]: bool(re.match('el', 'Hello', re.I))
Out[34]: False 

On a 2000-character string this is about 20x times faster than lower():

In [38]: s = 'A' * 2000

In [39]: %timeit s.lower().startswith('he')
10000 loops, best of 3: 41.3 us per loop

In [40]: %timeit bool(re.match('el', s, re.I))
100000 loops, best of 3: 2.06 us per loop

If you are matching the same prefix repeatedly, pre-compiling the regex can make a large difference:

In [41]: p = re.compile('he', re.I)

In [42]: %timeit p.match(s)
1000000 loops, best of 3: 351 ns per loop

For short prefixes, slicing the prefix out of the string before converting it to lowercase could be even faster:

In [43]: %timeit s[:2].lower() == 'he'
1000000 loops, best of 3: 287 ns per loop

Relative timings of these approaches will of course depend on the length of the prefix. On my machine the breakeven point seems to be about six characters, which is when the pre-compiled regex becomes the fastest method.

In my experiments, checking every character separately could be even faster:

In [44]: %timeit (s[0] == 'h' or s[0] == 'H') and (s[1] == 'e' or s[1] == 'E')
1000000 loops, best of 3: 189 ns per loop

However, this method only works for prefixes that are known when you're writing the code, and doesn't lend itself to longer prefixes.

2 of 7
39

How about this:

prefix = 'he'
if myVeryLongStr[:len(prefix)].lower() == prefix.lower()
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › string › endswith › python-string-endswith
Python endswith() function | Why do we use Python String endswith()? |
September 27, 2021 - Python endswith() is a string method that returns True if the input string ends with the specified suffix(string); else it returns False. Also, the Python endswith() function is case-sensitive.
🌐
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.
🌐
Abdul Wahab Junaid
awjunaid.com › home › case insensitive string comparisons in python
Case insensitive string comparisons in python | Abdul Wahab Junaid
August 14, 2023 - Python · string1 = "Straße" string2 ... str.endswith(): You can combine the str.lower() (or str.upper()) method with str.startswith() and str.endswith() methods to perform case-insensitive prefix or suffix checks....
🌐
Bowmanjd
bowmanjd.com › python-casefold
Case-insensitive string comparison in Python using casefold, not lower | Jonathan Bowman
July 15, 2020 - Here is a discipline I am trying to adopt in my Python programs: use "My string".casefold() instead of "My string".lower() when comparing strings irrespective of case. When checking for string equality, in which I don’t care about uppercase vs. lowercase, it is tempting to do something like this: if "StrinG".lower() == "string".lower(): print("Case-insensitive equality!")