Search code examples
pythonstringkeyword-argument

How to test several conditions with .endswith function in python


I have a list of files with different extensions. Out of those I want to filter out only those with extension .bam, .bai, .vcf and some more. Is there a way to do it using the endswith function with multiple arguments instead of repeating it multiple times?

So instead of:

for name in list:
    if name.endswith('.bam') or name.endswith('.bai') or name.endswith('.bai'):
        # do stuff

Something like:

for name in list:
    if name.endswith(*['.bai', '.bam', '.vcf']):
        # do stuff

Solution

  • endswith accepts a tuple of possible suffixes, as of Python 2.5. So it's just:

    if name.endswith(('.bai','.bam','.vcf')):
    

    https://docs.python.org/3/library/stdtypes.html#str.endswith