[Tutor] Searching list items.
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.
>>> 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.
or without the intermediate variable:
When you do a re search, you get a match object, which has methods such
well, Danny already gave you the site.
> match. Take a look at a few of the methods in here:
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)
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
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
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,
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)]
for item in substrs:
if item in line:
Whereas with a regular expression, you'd just do
regexp = re.compile('something\d\d')
Computationally the last example should be much more efficient.
clearly it's also more complicated if you don't know regular expressions
However, the substrs example is not too great either when it comes to
More information about the Tutor