2

I have a string representing a filename, how can I check it against few conditions at once? I've tried

if r'.jpg' or r'.png' not in singlefile:

but kept getting false positives all the time.

4 Answers 4

3

Your code is equal with:

if (r'.jpg') or (r'.png' not in singlefile):

You're, probably, looking for:

if r'.jpg' not in singlefile or r'.png' not in singlefile:

Or

if any(part not in singlefile for part in [r'.jpg', r'.png']):

Thanks to Tim Pietzcker:

He(you) actually (probably) wants

if not any(singlefile.endswith(part) for part in [r'.jpg', r'.png'])
#                     ^^^^^^^^
Sign up to request clarification or add additional context in comments.

2 Comments

Right. And he actually (probably) wants if not any(singlefile.endswith(part) for part in [r'.jpg', r'.png']).
Yeah using endswith is probably the best solution
2

This is because of precedence. Following code means.

# r'.jpg' is constant
if r'.jpg' or (r'.png' not in singlefile):

If constant, or .png not in singlefile. As constant is always true, the expression is always truthy.

Instead, you could try using regular expressions, to check whatever string fits a pattern.

import re
if re.match(r"\.(?:jpg|png)$", singlefile):

1 Comment

I'd prefer regex for check too, but you was faster. +1 anyway.
1

your problem is with the fact that your logical OR is checking a constant and a variable.

r'.png'

will always evaluate to True, thus making your or true as well.

you have to check for both, like so

if r'.png' not in singlefile or 'r.jpg'  not in singlefile:
    #do stuff

Comments

0

Try this:

if r'.jpg' not in singlefile or r'.png' not in singlefile:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.