'How to check if any of the multiple strings are not present in a string in Python [duplicate]
I have a String message
message = "The boy Akash is studying in 9th class at Boys school"
I wanted to check if any of the words boy
or class
or school
is not present. If any of those are not present it should show a error message.
if('boy' or 'class' or 'school' not in message):
print = "Please check if you have filled all data"
But when I tried this, even if all keywords are present its showing error. Where it could be wrong.
Solution 1:[1]
It doesn't work because what you wrote is not what you meant.
Consider the snippet:
if 'boy':
print("There's a boy here")
If you run it, you'll get:
>>> There's a boy here!
This is because by default, python consider all non-empty string as True
.
Therefore, to fix your code, you need to:
if('boy' not in message or 'class' not in message or 'school' not in message):
print = "Please check if you have filled all data"
or, equivalently:
for word in ['boy', 'class', 'school']:
if word not in message:
print = "Please check if you have filled all data"
Solution 2:[2]
Presumably you have to list out each expression separately:
if "boy" not in message or "class" not in message or "school" not in message:
print = "Please check if you have filled all data"
You could also use regex here, which would allow you to use word boundaries, for a possibly more reliable match:
match1 = re.search(r'\bboy\b', message)
match2 = re.search(r'\bclass\b', message)
match3 = re.search(r'\bschool\b', message)
if not match1 or not match2 or not match3:
print = "Please check if you have filled all data"
Solution 3:[3]
What is your error?
Your syntax should be:
if ('boy' not in message) or ('class' not in message) or ('school' not in message) :
print("Please check if you have filled all data")
If you have a conditional with multiple expressions, you must give each expression separated by a logical operator (or, and) , as above but also for more complex decision structures eg:
if ( (x < 2) and (y > 5) ) or (z == 0):
print("")
Note the print statement - you have tried to assign a string to a variable print
as opposed to using the print
function with a string as argument. As the print
keyword is reserved as a standard library function, you shouldn't be able to use it as a variable.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Tim Biegeleisen |
Solution 3 |