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
Top answer
1 of 1
2

You can create a set() of lower-case names and look up your p["Name"] in it:

@bot.command(pass_context=True)
async def ping(ctx, namesList):
  # sets are better for lookups. prepare a set with all lower case names 
  setOfNamesLowerCase = set ( x.lower() for x in namesList ) # dont name lists list
  with open('data.json') as json_file:
    d = json.load(json_file)
    for p in d['people']:
      if(p['Name'].lower() in setOfNamesLowerCase ):
        await bot.send_message(ctx.message.channel, p)

Sets are better suited for this task, lookup is O(1) and in case you have duplicates they get automatically reduced.


Logic reduced to check if it should work, given correct inputs:

def find_tata(namesList):
    # sets are better for lookups. prepare a set with all lower case names 
    setOfNamesLowerCase = set ( x.lower() for x in namesList ) # dont name lists list
    if "tata" in setOfNamesLowerCase:
        print("Its in")
    else:
        print ("Its not")


find_tata( ["not in here","not in"])
find_tata( ["not in here","tata"])

Output:

Its not
Its in

Edit 2:

import json

js = """{"people": [
    {"UserID": "xxxxx123", "Name": "Steve", "Sex": "Male", "age": "30"},
    {"UserID": "xxxxx124", "Name": "Rachel", "Sex": "Female", "age": "25"},
    {"UserID": "xxxxx125", "Name": "George", "Sex": "Male", "age": "22"} ] }"""

def ping(namesList):
    # sets are better for lookups. prepare a set with all lower case names
    setOfNamesLowerCase = set ( x.lower() for x in namesList ) # dont name lists list
    d = json.loads(js)
    for p in d['people']:
        if(p['Name'].lower() in setOfNamesLowerCase ):
            print("Doing smth for ", p["Name"]) 

ping(["rachEl", "ludwig", "ernie", "GEoRgE"])

Output:

Doing smth for  Rachel
Doing smth for  George
🌐
Stack Overflow
stackoverflow.com › questions › 71389455 › how-to-transform-key-from-json-data-case-insensitive-in-python
How to transform key from json data case insensitive in python? - Stack Overflow
I have a json which has data that comes from multiple sources and a particular field key is inconsistent in terms of case. For example there is one column as data which has jsons inside it. {"...
🌐
Stack Overflow
stackoverflow.com › questions › 61110159 › read-json-key-value-as-insensitive-key
python - Read json key value as insensitive key - Stack Overflow
You need to loop through all the keys of the dictionary until you find one that matches irr case-insensitively.
🌐
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?
🌐
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.
🌐
GitHub
github.com › psf › requests › issues › 1380
TypeError: CaseInsensitiveDict is not JSON serializable · Issue #1380 · psf/requests
May 22, 2013 - The recent change that makes header case insensitive dict makes it impossible to dump request headers into a JSON object. To reproduce this issue: >>> import requests >>> r = requests.get("http://google.com") >>> r.headers CaseInsensitiv...
Author: psf
Find elsewhere
🌐
Cknotes
cknotes.com › case-insensitive-json
Case-Insensitive JSON – Chilkat Tech Notes
The Answer: In v9.5.0.87, Chilkat added the JsonObject property LowerCaseNames: https://chilkatsoft.com/refdoc/csJsonObjectRef.html#prop14 When the JSON is loaded, the member names are converted to lowercase. This way you can always use lowercase names and thus the parsing becomes case-insensitive.
🌐
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() ...
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 to make it case sensitive we should add a third flag parameter matchCase like... var startsWith = str.startsWith(searchString [, position [, matchCase] ] ); var contained = str.contains(searchString [, position [, matchCase] ] ); var endsWith = str.endsWith(searchString [, position [, ...
🌐
Blogger
jpython.blogspot.com › 2013 › 12 › python-case-insensitive-dictionary.html
Life is very easy with Python: Python case insensitive dictionary
December 12, 2013 - class CaseInsensitiveDict(dict): def __setitem__(self, key, value): key = key.lower() dict.__setitem__(self, key, value) def __getitem__(self, key): key = key.lower() return dict.__getitem__(self, key) d = CaseInsensitiveDict() d["Python"] = "Easy" print d["PYTHON"] print d["python"] Output:
🌐
AskPython
askpython.com › python › string › python-string-endswith-function
Python String endswith() function - AskPython
August 6, 2022 - Python string endswith() function returns True if the input string ends with a particular suffix, else it returns False.
🌐
GitHub
github.com › networknt › json-schema-validator › issues › 31
How remove case sensitive for JSON keys · Issue #31 · networknt/json-schema-validator
May 15, 2017 - Schema mentioned: {"name" : ...} Passing payload : {"Name": ...} Error showing currently : "name" is required "Name" not allow additional property Kindly advise any option to ignore only case validation. I want to allow all case should a...
Author: networknt
🌐
Mathspp
mathspp.com › blog › how-to-work-with-case-insensitive-strings
How to work with case-insensitive strings | mathspp
January 21, 2023 - This is a short and practical tutorial that guides you on how to work with case-insensitive strings in Python and teaches how to use the str.lower,...
Author: fastapi