8.4. The in
and not in
operators¶
The in
operator tests if one string is a substring of another:
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
Note that a string is a substring of itself, and the empty string is a substring of any other string. (Also note that computer scientists like to think about these edge cases quite carefully!)
The not in
operator returns the logical opposite result of in
.
We can also use the in
and not in
operators on lists!
However, remember how you were able to check to see if an “a” was in “apple”? Let’s try that again to see if there’s an “a” somewhere in the following list.
Clearly, we can tell that a is in the word apple, and absolutely, and application. For some reason
though, the Python interpreter returns False. Why is that? When we use the in
and not in
operators on lists, Python checks to see if the item on the left side of the expression is equivalent
to an element in the item on the right side of the expression. In this case, Python is checking
whether or not an element of the list is the string “a” - nothing more or less than that.