Kristian Roebuck
Kristian Roebuck

Reputation: 3379

Python: How to test multiple values inside an if [multiple values] in list:

I have returned a list of href values from a HTML document. I want to go though every link within this list and test to see if they contain any of the values within my IMAGE_FORMAT tuple.

IMAGE_FORMAT = (
    '.png',
    '.jpg',
    '.jpeg',
    '.gif',
)

At present I am simply testing for '.jpg' e.g if '.jpg' in link.get('href'):

I'd like to extend this code to something along the lines of if [any value inside IMAGEFORMAT] in link.get('href'):

What would be the most efficient or cleanest way or doing so?

Upvotes: 0

Views: 3240

Answers (2)

cheeken
cheeken

Reputation: 34685

Try any against list comprehension.

any(e in href for e in IMAGE_FORMAT)

Or, in English, "are any of the items in my image formats in my URI?" Bare in mind how in functions with strings, though.

Upvotes: 1

DSM
DSM

Reputation: 353569

If you really want in, then maybe

href = link.get('href')
if any(end in href for end in IMAGE_FORMAT):
    # do something
    pass

but if you actually want ends with, then use .endswith:

>>> IMAGE_FORMAT = ('.png','.gif','.jpg','.jpeg')
>>> 'fred.gif'.endswith(IMAGE_FORMAT)
True

Depends on how you want to treat 'fred.gif.gz', etc. Also note you might want to work with href.lower() if you don't care about case.

Upvotes: 6

Related Questions