1

I have a list and I have a given string. The list looks like the following:

["hello, whats up?", "my name is...", "goodbye"]

I want to find the index in the list of where the given string is, for example:

  • If the given string is "whats" I want it to return 0
  • If the given string is "name" it'll be returning 1

I tried to use list_name.index(given_string) but it says "whats" is not in the list.

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
  • Does this answer your question? [Finding the index of an item in a list](https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list) – Anil Jun 09 '20 at 15:49

2 Answers2

3

That is because whats is not really present in the list. The list actually has "hello, whats up?". So if you set the value of given_string to be like - given_string = "hello, whats up?", then you will get 0 as index. The index method just compares the values, in this case entire string. It does not check for values within the string.

Edit 1: This is how I would do it:

list = ["hello, whats up?", "my name is...", "goodbye"]
for index, string in enumerate(list):
     if 'whats' in string:
             print index
Raj Kumar
  • 1,547
  • 14
  • 19
0

You could do something like the follwoing:

l = ["hello, whats up?", "my name is...", "goodbye"]
sub_s = "name"
indx = [i for i, s in enumerate(l) if sub_s in s]
print(indx) # [1]

This is more robust in the case where you have more then 1 index

David
  • 8,113
  • 2
  • 17
  • 36