Having fun with Python

23 Jul

I was doing some lightweight scripting like this:

pattern = re.compile("searchingFor", re.IGNORECASE)

tables = [];
for line in fp.readlines():
    if pattern.search(line):
        tables += line
return tables

And then I remembered how fun Python could be with things like the list comprehensions:

pattern = re.compile("searchingFor", re.IGNORECASE)
return [ line for line in fp.readlines()
                if pattern.search(line) ]

Nice, huh? If you want to find out more about mapping lists, keep reading here.

Update: Even better! Cleanear, intuitive, two liner… hell yeah!

pattern = re.compile("searchingFor", re.IGNORECASE)
return filter( pattern.search, fp.readlines() )

Comments are closed.