Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string ends with one of the strings from a list

People also ask

How do you check if string ends with one of the strings from a list?

Method #1 : Using filter() + endswith() The combination of the above function can help to perform this particular task. The filter method is used to check for each word and endswith method tests for the suffix logic at target list.

How do you check if a string ends with a string in Python?

The endswith() function returns True if a string ends with the specified suffix (case-sensitive), otherwise returns False. A tuple of string elements can also be passed to check for multiple options. If a string ends with any element of the tuple then the endswith() function returns True.

How do you check if a string ends with a?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.


Though not widely known, str.endswith also accepts a tuple. You don't need to loop.

>>> 'test.mp3'.endswith(('.mp3', '.avi'))
True

Just use:

if file_name.endswith(tuple(extensions)):

Take an extension from the file and see if it is in the set of extensions:

>>> import os
>>> extensions = set(['.mp3','.avi'])
>>> file_name = 'test.mp3'
>>> extension = os.path.splitext(file_name)[1]
>>> extension in extensions
True

Using a set because time complexity for lookups in sets is O(1) (docs).


There is two ways: regular expressions and string (str) methods.

String methods are usually faster ( ~2x ).

import re, timeit
p = re.compile('.*(.mp3|.avi)$', re.IGNORECASE)
file_name = 'test.mp3'
print(bool(t.match(file_name))
%timeit bool(t.match(file_name)

792 ns ± 1.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

file_name = 'test.mp3'
extensions = ('.mp3','.avi')
print(file_name.lower().endswith(extensions))
%timeit file_name.lower().endswith(extensions)

274 ns ± 4.22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)


another way which can return the list of matching strings is

sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']

I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

I have this:

def has_extension(filename, extension):

    ext = "." + extension
    if filename.endswith(ext):
        return True
    else:
        return False