Andy S. C.
Andy S. C.

Reputation: 368

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

Upvotes: 3

Views: 3397

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37354

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

Upvotes: 10

Related Questions