how to find a substring in python code example

Example 1: python find all elements of substring in string

def find_all(a_str, sub):
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1: return
        yield start
        start += len(sub) # use start += 1 to find overlapping matches

list(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]

Example 2: python check if string

type('hello world') == str
# output: True

type(10) == str
# output: False

Example 3: python check if value in string

def is_value_in_string(value: str, the_string: str):
    return value in the_string.lower()

Tags: