chow chow - 7 months ago 16
Python Question

Find an entry in a list based on a partial string

I have this list:

item = ['AAA:60', 'BBB:10', 'CCC:65', 'DDD:70', 'EEE:70']


and then I get this string passed to me:

widget = 'BBB'


I'd like to find the entry in
item
based on
widget
.

I want to find the entry in the list if
widget
is contained in any of the list entries. Something where I can use
item[i]
and preserve the list for the loop it will endure.

Final output would be the list entry itself,
BBB:10
. (In the example provided.)

Answer

You can try:

>>> item = ['AAA:60', 'BBB:10', 'CCC:65', 'DDD:70', 'EEE:70']
>>> widget = 'BBB'

>>> next(i for i in item if i.startswith(widget))
'BBB:10'

Or if it doesn't necessarily have to begin with "BBB" then you can change the condition to

>>> next(i for i in item if widget in i)
'BBB:10'
>>> next(idx for idx,i in enumerate(item) if widget in i)
1

EDIT: Please also read @PaulMcGuire's answer. In terms of design that is how it should be done.