1

First I check a given condition, as per a normal IF statement. If it is True, I need to scan all files for a single keyword. If it is not True, I need to scan all files for a set of keywords, which will have been supplied.

For my simple working example, rather than scanning file names in a directory, I simply search a string for the keywords.

test1 = "NotKeyWord"
password = "password"
password1 = "password1"
password2 = "password2"
password3 = "password3"

if test1.lower() == "keyword":
    condition = password
else:
    condition = [password1, password2, password3]

f = "password1_password2_password3_jibberish_E=mc2"
if condition in f:
    print("Problem solved")

If the keyword = "keyword" i.e., is singular, then this code works. Fine. However, I would like to make it so that if it is the other case, which requires knowing several keywords to grab the right file, I don't need to resort to explicitly writing out all the words.

For my purposes I could write

if password1 in f and password2 in f and password3 in f:
    print("problem solved")

But I am after a pythonic method, that will hopefully be generic enough to be able to handle an array of keywords that is of unknown length, and thus can't be hard coded.

0

4 Answers 4

4

This should work,

if all ( c in f for c in condition ):
    print("problem solved")
Sign up to request clarification or add additional context in comments.

2 Comments

The problem here is that if any of them are true, it passes, but I need ALL of them to be true
Okay, you can change to the condition to all(). I have edited it
3

Make condition always be a list, even if it only has one item:

if test1.lower() == "keyword":
    condition = [password]
else:
    condition = [password1, password2, password3]

Then use the all() function to check if all elements in condition are present in f:

if all(c in f for c in condition):
    print("problem solved")

This will work whether condition has one element, or ten, or a hundred.

1 Comment

amen. I will flip a coin to see who gets it since Nebiyou had it too, just with the "any" rather than "all"
1

One way is:

if [x for x in condition if x in f]:
   ...

Comments

1

To make it easier for yourself, I would make a list of passwords in both cases. If test1 is the keyword then it just becomes a list of one.

if test1.lower() == "keyword":
    passwords = [password]
else:
    passwords = [password1, password2, password3]

Then you can use Python's built-in all function with a generator expression for the second condition.

f = "password1_password2_password3_jibberish_E=mc2"
if all(pw in f for pw in passwords):
    print("Problem solved")

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.