Computer Science · Ch 8 — Strings
Membership
Membership
Python provides two membership operators for strings: in and not in. Both take two strings and answer a yes/no question about whether the first occurs inside the second, returning a Boolean value (True or False).
The in operator
in takes two strings and returns True if the first string appears as a substring of the second, and False otherwise. A substring is any unbroken run of characters within the string — a single character, a partial word, or a whole word:
>>> s = 'Learn Python well'
>>> 'P' in s # single character present
True
>>> 'Pyt' in s # partial word present as a contiguous run
True
>>> 'Java' in s # never occurs in s
False
Note that the match must be contiguous — the characters of the first string must appear together, in order, inside the second string.
The not in operator
not in is the exact opposite. It also takes two strings, and returns True if the first string does not appear as a substring of the second; if the substring is present, it returns False:
>>> s = 'Learn Python well'
>>> 'Java' not in s # indeed absent
True
>>> 'Learn' not in s # actually present, so... …