[Tutor] How to find a substring within a list of items

Wayne Werner waynejwerner at gmail.com
Thu Jan 13 20:27:17 CET 2011


On Thu, Jan 13, 2011 at 12:10 PM, Richard Querin <rfquerin at gmail.com> wrote:

> I have an object that contains about 3500 list items, each list containing
> various data, some strings and some floats, like so:
>
> ['D', 123.4,'This is a project description', 'type', 52.1,'title']
>
> What is the easiest way to search this list for a given string? So I want
> to find out if this list contains the string 'scrip' anywhere within it
> (case insensitive and including being just part of a larger string).
>
> Incidentally, I'm using the xlrd module to read in a spreadsheet. I
> effectively want to quickly pull out a list of lines from that spreadsheet
> that contain that substring anywhere within them. Maybe there is a
> better/faster way I should be doing this?
>
> I'm trying to give employees here a better/faster way of filtering through
> the company project list rather than opening up excel and doing a find
> search each time.
>

Well, the easiest (maybe not fastest) way would be something like:

rows_found = []
for row in rows:
    for element in row:
        try:
            if 'scrip' in element:
                 rows_found.append(row)
                 break # Once we find an element, no need to check others
        except TypeError:
            pass #can't iterate over int's & such

That should give you the correct results.

Alternatively, if you have something against try/except you could do

for row in rows
    if 'scrip' in str(row): #str(row) turns the list into the same thing you
get when you print(row)
        rows_found.append(row)

I'm not sure which one is faster, though I presume the first one would be.

I don't know if either of these are the best options (they probably aren't),
but they should work, and for 3500 it will probably loop faster than opening
up excel.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110113/7b059140/attachment-0001.html>


More information about the Tutor mailing list