Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the index of a string ignoring cases

Tags:

python

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.

like image 860
Process1 Avatar asked Mar 14 '13 22:03

Process1


1 Answers

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.

like image 142
Asad Saeeduddin Avatar answered Sep 19 '22 11:09

Asad Saeeduddin