[Tutor] Text matching and replacing
Tiger12506
keridee at jayco.net
Wed Jul 25 23:31:37 CEST 2007
> Cheers for the critique I'll take you points on board .....especially
> this schoolboy error
It's not an error, really. It will work. Just... not intuitive
Errors are things that do not work.
> One thing to note about the re expression is that the products are not
> <product n> these were just substitutes. In reality these are product
> names with no commonality e.g. ('baked beans'|'tuna'|'salad')
>
> So with that in mind is the way I have set the re way the best way or is
> there an another more pythonic way.
I can't tell you one way or the other, (and I have a hard time determining
that which makes something more or less pythonic) but i have noticed that
using re expressions for fixed patterns like that (no special identifiers,
etc.) is considered overkill. It is easier to use string methods.
> As an aside I don't believe there were any tips in there to help solve
> the problems I have...again any help would be warmly appreciated.
However, the answer to your problem may be that you could rely on re
expressions more than you are. What I like about regular expressions is the
sheer power. Watch.
import re
teststring = """
Name: Jacob Schmidt
Address: 1234 Fake Street
City: Nowhere
State: Indiana
Zip Code: 14241
Name: Tiger Power
Address: 4321 Mysterious Lane
City: Jersey
State: Indiana
Zip Code: 14051-1390
"""
pat = re.compile(r".*Name: (.*)\nAddress: (.*)\nCity: (.*)\nState: (.*)\nZip
Code: (\d{5}(?:-\d{4})?).*")
lst = pat.findall(teststring)
for x in lst:
print x
##############################################
I'm sure this will help you some. :-)
JS
More information about the Tutor
mailing list