Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to use “in” to find string characters in Python

Onyejiaku Theophilus Chidalu

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 string
axiom = 'Nothing worth while ever is'

# using the in keyword
print('never' in axiom)
print('ever' in axiom)
Using the "in" keyword

Code explanation

  • Line 2: We create a string variable, axiom.
  • Line 5: We check if the character never is present in the string we created.
  • Line 6: We check if the character ever is present in the string we created.

Example

The in keyword can also be used in an if statement.

# creating a string
axiom = 'Nothing worth while ever is'

# using the if statement
if 'ever' in axiom:
    print("True! The word 'ever' is present in the string.")
Using the "in" keyword in an "if" statement

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.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring