Regex: Perl to Python
Chris Angelico
rosuav at gmail.com
Sun Mar 6 23:45:26 EST 2016
On Mon, Mar 7, 2016 at 3:38 PM, Fillmore <fillmore_remove at hotmail.com> wrote:
> pattern = re.compile(r"(\d+)\t(.+)$")
> with open(fields_Indexfile,mode="rt",encoding='utf-8') as headerfile:
> for line in headerfile:
> #sys.stdout.write(line)
> m = pattern.match(line)
> print(m.group(0))
> headerfile.close()
>
> but I must be getting something fundamentally wrong because:
>
> Traceback (most recent call last):
> File "./slicer.py", line 30, in <module>
> print(m.group(0))
> AttributeError: 'NoneType' object has no attribute 'group'
>
>
> why is 'm' a None?
When the regex doesn't match, Python gives you back None instead of a
match object. Your Perl code has an 'if' to guard that; you can do the
same thing:
if m:
print(m.group(0))
ChrisA
More information about the Python-list
mailing list