Search a string

See also Common Sequence Operations.

Search a string with in or not in

s = "counterclockwise"

if "clock" in s:
    print(f'"{s}" contains "clock".')   #double quotes in a single quoted string literal
else:
    print(f'"{s}" does not contain "clock".')
"counterclockwise" contains "clock".

Search a string with index

See also rindex.

s = "counterclockwise"

try:   #EAFP
    i = s.index("clock")
    print(f'"{s}" contains "clock" at index {i}.')
except ValueError as error:
    print(f'"{s}" does not contain "clock": {error}.')
"counterclockwise" contains "clock" at index 7.
"counterclockwise" does not contain "dock": substring not found.

Search a string with find

See also rfind. find and rfind are the same as index and rindex except that the former indicate failure by returning a negative number, while the latter indicate failure by raising the ValueError exception.

s = "counterclockwise"

i = s.find("clock")
if i >= 0:   #LBYL
    print(f'"{s}" contains "clock" at index {i}.')
else:
    print(f'"{s}" does not contain "clock".')
"counterclockwise" contains "clock" at index 7.

Search a string with a regular expression

See parentheses and vertical bars.

"""
Search for a regular expression in a string.
"""

import sys
import re

s = "He is the most prochoice candidate."
regularExpression = "(pro|anti)(choice|life|abortion)"   #6 possibilities

try:
    m = re.search(regularExpression, s)   #m is a Match object.
except re.error as error:
    print(error, file = sys.stderr)
    sys.exit(1)

if m:
    print(f'Found "{m.group()}" at index {m.start()}.')
else:
    print("no match")

sys.exit(0)
Found "prochoice" at index 15.

What happens if you change the regular expression to one of the following?

regularExpression = "pro|antichoice|life|abortion"      #removed the two pairs of parentheses
regularExpression = "pro|anti(choice|life|abortion)"    #removed one pair of parentheses
regularExpression = "(pro|anti)(choice|life|abortion)(" #added one extra parenthesis