python find substring 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)
list(find_all('spam spam spam spam', 'spam'))
Example 2: python get a substring of a string
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
Example 3: find string in string python
>>> str = "Messi is the best soccer player"
>>> "soccer" in str
True
>>> "football" in str
False
Example 4: find in python
def find_all_indexes(input_str, search_str):
l1 = []
length = len(input_str)
index = 0
while index < length:
i = input_str.find(search_str, index)
if i == -1:
return l1
l1.append(i)
index = i + 1
return l1
s = 'abaacdaa12aa2'
print(find_all_indexes(s, 'a'))
print(find_all_indexes(s, 'aa'))
Example 5: Find substring into a string - Python
if "blah" in somestring:
continue