Is It in There?
The problem...
You have a value. You want to know if it exists somewhere.
Is this letter in the word? Is this word in the sentence?
You could check character by character. But that's slow, messy, and unnecessary.
The idea!
Python has a keyword that does exactly this in one word: in.
It checks if something exists inside something else. And it always returns a bool.
Making it real
message = "Hello Bull"
print("Bull" in message) # True
print("Horn" in message) # False
One line. One answer. True or False.
In practice
name = "RedHornDev"
print("Horn" in name) # True
print("horn" in name) # False — case sensitive
print("Red" in name) # True
print("Dev" in name) # True
print("dev" in name) # False
in is case sensitive — exactly like everything else in Python.
not in
You can flip it with not:
message = "Hello Bull"
print("Horn" not in message) # True — Horn is NOT in message
print("Bull" not in message) # False — Bull IS in message
not in is the natural opposite of in.
Going further
You've already seen in with strings. But it works with other types too — you'll see that in the Data Structures chapter.
username = input("Enter your username: ")
banned = "admin"
print(banned in username) # True if "admin" appears anywhere in the username
What's really happening
in searches through the sequence and returns True if it finds a match, False if it doesn't.
It's not magic — it's a check. And the result is always a bool.
Heads up!
inis case sensitive —"bull"and"Bull"are not the samenot inis two words — clean and readableinworks on strings now — and on lists and dicts later
The mindset shift
Stop thinking: "I need to write a loop to check if something exists."
Start thinking: "Python has in. One word. One answer."
What you should understand now
inchecks if a value exists inside another value- It always returns a bool
not inis the oppositeinis case sensitive