find a substring in a string 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: python string in string
>>> str = "Messi is the best soccer player"
>>> "soccer" in str
True
>>> "football" in str
False
Example 4: how to check for a substring in python
def find_string(string,sub_string):
return string.find(sub_string)
Example 5: Find substring into a string - Python
if "blah" in somestring:
continue