How to use “in” to find string characters in Python
Overview
In Python, a string is a sequence of characters or text that is enclosed with either single quotes (' ') or double quotes (" ").
For example, 'Theo' is a string. Whether the characters are enclosed in single quotes or double quotes, it is still the same string; in other words, 'Theo' is the same as "Theo".
The in keyword
The in statement is used to check if a character or sequence of characters is present in a string.
Return value
The return value of the in keyword is either True or False.
Example
# creating a stringaxiom = 'Nothing worth while ever is'# using the in keywordprint('never' in axiom)print('ever' in axiom)
Code explanation
- Line 2: We create a string variable,
axiom. - Line 5: We check if the character
neveris present in the string we created. - Line 6: We check if the character
everis present in the string we created.
Example
The in keyword can also be used in an if statement.
# creating a stringaxiom = 'Nothing worth while ever is'# using the if statementif 'ever' in axiom:print("True! The word 'ever' is present in the string.")
Code explanation
In the code above, we use the in keyword to check if the word 'ever' is present in the string we created, and we get True as the result.