What is the not in keyword in Python?

Overview

Strings in Python is a sequence of characters or text that are enclosed with either a single quote (' ') or a double quote (" ").

For example, 'Theo' is a string. Whether the characters are enclosed in a single or double quote, it is still the same string; 'Theo' is the same as "Theo".

How to use the not in keyword

The not in statement is used to check if a character or sequence of characters is not present in a string.

Return value

The return value of the not in keyword is either TRUE or a FALSE.

Example

# creating a string
axiom = 'Nothing worth while ever is'
# using the not in keyword
print('never' not in axiom)

Explanation

In the code above, we check if the word 'never' is present in a given string. We expect it returns True because the word 'never' can not be found in the string 'Nothing worth while ever is'.

Interestingly the not in keyword can also be used in an if statement.

Example

# creating a string
axiom = 'Nothing worth while ever is'
# using the if statement
if 'never' not in axiom:
print("False! The word 'never' is not present.")

Explanation

In the code above, we use the not in keyword to check if the word 'never' is not present in the string we created. And as expected, it is not.

Free Resources