'Find a individual word location in a list that isn't its own value
I am trying to find a specific word in a list. As simple as it sounds, me and the people I've talked to can't think of an answer. Below is an example of my issue.
list = ['this is ', 'a simple ', 'list of things.']
I want to find the word "simple"
in the list, and note its location. (Aka list[1]
in this example.)
I've tried a few methods, for example:
try:
print(list.index("simple"))
except (ValueError) as e:
print(e)
Which will always return as 'simple'
is not in list.
Any ideas on what I can do to solve this?
Solution 1:[1]
This is because list.index function searches for occurence of exact 'simple' string in the list, i.e. it does not do any substring searches. To complete your task you can use in
operator and do comparison for every string in a list:
my_list = ['this is ', 'a simple ', 'list of things.']
def find_string(l, word):
for i, s in enumerate(l):
if word in s:
return i
else:
raise ValueError('"{}" is not in list'.format(word))
try:
print(find_string(my_list, "simple"))
except ValueError as e:
print(e)
Solution 2:[2]
You need to iterate over each element in the list, and the determine if your word is in the list. You can define a function to handle this:
def word_check(my_list, word):
for i in range(0, len(my_list)):
if word in my_list[i]:
return i
return False
list = ['this is ', 'a simple ', 'list of things.']
word_check(list, 'simple')
The function will return the index of the word if found, else it will return false.
Solution 3:[3]
You can loop through list and check if the word is in the list items and get its index by making a variable. Here is a sample code:
list = ['this is ', 'a simple ', 'list of things.']
word = "simple"
for item in list:
if word in item:
print(list.index(item))
break
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | leotrubach |
Solution 2 | John |
Solution 3 |