Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using endswith with case insensivity in python

I have a list of file extensions and I have to write if conditions. Something like

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.endswith(tuple(ext)) for filename in filenames]):

I realized that endswith is case sensitive. How I could treat, for instance, ".xml" and ".XML" as the same extensions?

like image 921
edyvedy13 Avatar asked Aug 11 '17 14:08

edyvedy13


People also ask

Is Endswith case-sensitive Python?

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.

How do you use case-insensitive in Python?

Approach No 1: Python String lower() Method This is the most popular approach to case-insensitive string comparisons in Python. The lower() method converts all the characters in a string to the lowercase, making it easier to compare two strings.

How do you ignore case-sensitive in Python?

Use str.lower() to lowercase all characters in a string. Use this when comparing two strings to ignore case.

What does Endswith () do in Python?

The endswith() method returns True if the string ends with the specified value, otherwise False.


1 Answers

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]):
like image 118
jdehesa Avatar answered Sep 19 '22 18:09

jdehesa