Say I have a list of strings like: ["Hey dude", "Hey bro", "Sup dude", "Hey bud"]
How do I check if *any* of those strings in the list contain the word "Sup"?Alternatively, in my case, I could also check if *all* of the strings contain "Hey" , which I also don't know how to do.
(Sorry, I'm new to Python)
Edit: Thank you so much for all the help, guys <3
I have a list, that takes inputs from the user, this means it can change size; for example: list = ["test", "do"] or list = ["a", "b", "c"]
I want to check if variable string, contains all the substrings in list.
I thought if I used:
if list in string: that would work, but it didn't, TypeError: 'in <string>' requires string as left operand, not list
Is there another function/method for this? Or am I going to have to loop len(list) times (I really don't want to do that, because I check hundreds of changing strings)?
You could try
if all([val in string for val in list]):
Which checks the truth of each check and returns True only if all are True. Otherwise you're looking at a loop (or if your lists get really big a generator).
I don't really understand your question, but the easiest to understand solution is probably
if len(set(sub) - set(super)) > 0:
Another one, straightforward, but more complex, is
if all(el in sub for el in super):
To check for the presence of 'abc' in any string in the list:
xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in xs):
...
To get all the items containing 'abc':
matching = [s for s in xs if "abc" in s]
Just throwing this out there: if you happen to need to match against more than one string, for example abc and def, you can combine two comprehensions as follows:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
Output:
['abc-123', 'def-456', 'abc-456']