9. Substring check

The in operator checks whether a substring appears inside a string. It returns a boolean:

It is an operator, not a function, so it is written between two values: substring in text. not in is the opposite:

The check is case-sensitive and looks for the exact sequence of characters, so "python" in "Python" is False.

To find where a substring appears, use the find() method:

  • sub — the substring to look for.
  • It returns the index of the first occurrence, or -1 when the substring is not there.

In this lesson you only need the one-argument form. The full method also accepts optional start and end indexes that limit the search.

Coming from JavaScript? sub in text is .includes(). To get a position use text.find(sub), which returns -1 when missing, like indexOf().

#01

Find a substring

substring in text checks whether the exact sequence of characters appears inside text. It produces True or False.

Print whether "thon" appears in "Python".

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

A substring that is missing

in returns False when the substring does not appear at all.

Print whether "Java" appears in "Python".

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Case matters

The in operator compares the exact characters, including their case.

Print whether "python" appears in "Python".

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Check for a missing symbol

not in is the opposite of in: it returns True when the substring does not appear.

Create a variable named email with the value "ada.example.com". Print whether "@" is not in email.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Find the position

find(sub) returns the index of the first occurrence of sub, or -1 when it is not there.

Print the result of finding "t" in "Python" using the one-argument form of find().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

When find returns -1

find() uses -1, not False, to report that the substring is missing.

Print the result of finding "z" in "Python" using the one-argument form of find().

Print exactly:

Create a free account to save your progress and unlock chapter 2.