chow chow - 1 year ago 46
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
based on

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

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

Answer Source

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))

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)
>>> next(idx for idx,i in enumerate(item) if widget in i)

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