[Tutor] Searching list items.

Luke Paireepinart rabidpoobear at gmail.com
Wed Oct 18 07:50:06 CEST 2006


Chris Hengge wrote:
> Not sure if you were challenging me to think, or asking me, but I was 
> wanting to "line" to be printed... as in the string from the list. 
> What I got with re was what I'm assuming was a memory address.
What you got was an object.  If you try to print an object, all you get 
is the name of the object and the memory address of the object.
def aFunction():
    print 'hi'

 >>> x = aFunction
 >>> print x
<function aFunction at 0x009E7870>

This is pretty useless, as Danny said.
what you want to do is actually use the object.
 >>> x()
hi

or without the intermediate variable:
 >>> aFunction()
hi

When you do a re search, you get a match object, which has methods such 
as...
well, Danny already gave you the site.
>
>     match.  Take a look at a few of the methods in here:
>
>          http://www.python.org/doc/lib/match-objects.html
>     <http://www.python.org/doc/lib/match-objects.html>
>

Does this explanation help?

so if you just want to print the line, all you would do is check whether 
the re.search() call returned None or a match object.

As John Fouhy said:

for line in contents:
    m = re.search('something', line)
    if m:
        print line[m.start():m.end()]

This example prints the portion of the line that matched the string you're searching for.

if you just want to print the line if it matches,
simply change the last line in the example to 'print line'.
note that the line
'if m'
could be rewritten
'if m != None:'

Or even (this may be Too Much Magic, so beware ;) )
'if m is not None'

For more advanced matching, you can actually use the match object that 
is returned.
but if you're just searching for a substring, then this will work.
Another good reason to use regular expressions is if you wanted to find, 
say,
the substring 'substring' with a 2-digit number on the end,
you'd have to do something like
substrs = ['substring'+str(a).zfill(2) for a in range(0,100)]

then
for item in substrs:
    if item in line:
       print line

Whereas with a regular expression, you'd just do
regexp = re.compile('something\d\d')

then
if regexp.search(line):
    print line

Computationally the last example should be much more efficient.
clearly it's also more complicated if you don't know regular expressions 
very well.
However, the substrs example is not too great either when it comes to 
readability.

HTH,
-Luke


More information about the Tutor mailing list