find substring in string 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)
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: how to check for a substring in python
def find_string(string,sub_string):
return string.find(sub_string)