0

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.

3 Answers 3

1
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]
Sign up to request clarification or add additional context in comments.

1 Comment

Let's say my list is MyList = ['acdef','GFDGFDG gfdgfd', 'Blue234 Sky2bas', 'Superman.424', 'base ball'] MyString = 'base b' I get [0]. How can I cover strings with spaces?
0

You can do it in one line using iterators.

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

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.