I am trying to print the index of the word in this string below. The problem right now is that it is checking for each element in the list and returning false. How can I make it return "False" if the word isn't in the list and not check it each element?
target = "dont"
string = "we dont need no education we dont need to thought control no we dont"
liste = string.split()
for index, item in enumerate(liste):
if target in item:
print index, item
else:
print 'False'
Output:
False
1 dont
False
False
False
False
6 dont
False
False
False
False
False
False
13 dont
check if the word is in the list first:
if word not in liste:
So if you want to return put it in a function:
def f(t, s):
liste = s.split()
if t not in liste:
return False
for index, item in enumerate(liste):
if t == item:
print index, item
return True
Unless you want to match substrings it should also be if t == item:
, If you want to return all the indexes you can return a list comp:
def f(t, s):
liste = s.split()
if t not in liste:
return False
return [index for index, item in enumerate(liste) if t == item]