Perl Hacker, Python Initiate
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Feb 2 20:08:37 EST 2011
On Wed, 02 Feb 2011 11:00:11 -0500, Gary Chambers wrote:
> Finally, the problem I encountered in the Python code was having the
> script fail when it encountered a line that didn't match either of the
> two regular expressions. What I'm seeking is either some Python code
> that mimics what my Perl script is doing, or to be shown the Python way
> of how to accomplish something like that.
I'd start with something like this:
lines = ... # wherever you are getting your input from
for line in lines:
if condition1(line):
process1(line)
elif condition2(line):
process2(line)
If neither condition1 nor condition2 are true, the loop will just go onto
the next line. Obviously the condition* and process* are just place-
holders.
> Surprisingly, there's no
> mention of regular expressions in the Perl Phrasebook at
> http://wiki.python.org/moin/PerlPhrasebook.
Perhaps your browser's "find" command is broken, because I count nine
matches. I don't know if any of them are useful or not.
The basic technique for using regular expressions in Python is:
import re # regexes are not built-in
mo = re.search(r"\b\w*ish\b", "Nobody expects the Spanish Inquisition!")
if mo is not None:
mo.group()
=> 'Spanish'
You don't have to use raw string r"", you can manually escape the
backslashes:
r"\b\w*ish\b" <=> "\\b\\w*ish\\b"
--
Steven
More information about the Python-list
mailing list