LaGuille
LaGuille

Reputation: 1728

Finding the index of a string within another string in a list in Python

I want the find the index of the string that contains another string within a list of n items.

MyList = ['acdef','GFDGFDG gfdgfd', 'Blue234 Sky2bas', 'Superman.424', 'baseball']
MyString = 'ball'

I want to get 4, since 'baseball' contains 'ball'

When looking for the exact string, I could use something like

MyList.index(MyString)

but this won't work with the above scenario since 'ball' is only a portion of 'baseball'.

I am also wondering what would happen if I search for a string like 'bas' considering the fact that it's in the 3rd and 5th items of the list.

Upvotes: 0

Views: 80

Answers (3)

LaGuille
LaGuille

Reputation: 1728

[i for i, s in enumerate(MyList) if MyString in s]

does what I was looking for and works in strings containing spaces

Upvotes: 0

levi
levi

Reputation: 22697

You can do it in one line using iterators.

(i for i,v in enumerate(l) if MyString in i).next()

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

MyList = ['acdef','GFDGFDG gfdgfd', 'Blue234 Sky2bas', 'Superman.424', 'baseball']
MyString = 'ball'

>>> [i.find(MyString) for i in MyList if MyString in i]
[4]

Another example, where 'ball' appears multiple times:

>>> MyOtherList ['foo', 'bar', 'football', 'ballbag', 'foobar']
>>> [i.find(MyString) for i in MyOtherList if MyString in i]
[4, 0]

Upvotes: 1

Related Questions