Fillmore wrote: > > Hi, I'm trying to move away from Perl and go to Python. > Regex seems to bethe hardest challenge so far. > > Perl: > > while (<HEADERFILE>) { > if (/(\d+)\t(.+)$/) { > print $1." - ". $2."\n"; > } > } > > into python > > 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?
match() matches from the begin of the string, use search(): match = pattern.search(line) if match is not None: print(match.group(1), "-", match.group(2)) Also, in Python you often can use string methods instead of regular expressions: index, tab, value = line.strip().partition("\t") if tab and index.isdigit(): print(index, "-", value) > the input data has this format: > > : > 3 prop1 > 4 prop2 > 5 prop3 > -- https://mail.python.org/mailman/listinfo/python-list