prayerShawl
prayerShawl

Reputation: 21

List index find by given string

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:

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

Upvotes: 1

Views: 2137

Answers (2)

Raj Kumar
Raj Kumar

Reputation: 1587

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

Upvotes: 3

David
David

Reputation: 8298

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

Upvotes: 0

Related Questions