简体   繁体   中英

find the index of a string ignoring cases

I have a string that I need to find index in a list ignoring cases.

MG
['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']

I want to find the index of MG in the following line as a list.

One of the more elegant ways you can do this is to use a generator:

>>> list = ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> next(i for i,v in enumerate(list) if v.lower() == 'mg')
3

The above code makes a generator that yields the index of the next case insensitive occurrence of mg in the list, then invokes next() once, to retrieve the first index. If you had several occurrences of mg in the list, calling next() repeatedly would yield them all.

This also has the benefit of being marginally less expensive, since an entire lower cased list need not be created; only as much of the list is processed as needs to be to find the next match.

you can ignore the cases by converting the total list and the item you want to search into lowercase.

>>> to_find = 'MG'
>>> old_list =  ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> new_list = [item.lower() for item in old_list]
>>> new_list.index(to_find.lower())
3

Same as first but I don't think there is need to create a new and old list if you are only interested in the index

>>> search_term ="MG"
>>> my_list = ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> [item.lower() for item in my_list ].index(search_term .lower())
3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM