I’m trying to teach myself Python, and I’ve got a reasonably simple task set out for myself. Basically, I want to read in a comma-delimited file, get the individual fields, and do some stuff with them. In Perl, what I’m trying to do is fairly simple:
Oy vey. First of all, you’d do much better using split in Perl for that task. Python also has a split method which you can call on any string object. To split a string foo on commas:
Python has pretty good support for regexes (though they don’t have every feature that Perl’s do.) To use one, you create and compile a regex object, then call its ‘match’ method against a string. You can then extract the capture groups from the resulting match object.
import re
pat = re.compile( '\((\d+)\) (\d+)-(\d+)' )
capt = pat.match( '(123) 555-1234' )
print capt.group( 1, 2, 3 )
(Note: the above is untested as I don’t have Python installed here at work. Hopefully it’s enough to get you started. There’s a pretty good tutorial on Python regexes here. )