[Tutor] Question on regular expressions

Alan Gauld alan.gauld at freenet.co.uk
Thu May 25 22:54:59 CEST 2006


> for line in open(r'e:\pycode\out_test.txt','rb') :
>    output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
> 16))) % ord(s.group()), line))
>
> This generated the traceback:
>
> File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8
>    output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(),
> 16))) % ord(s.group()), line))
>
>                         ^
> SyntaxError: invalid syntax
>
>
> By any chance, do you see where the syntax issue is?

Andrew, This is a good place to use the Python interactive prompt.
Try the various bits in the interpreter to find out what causes the 
error.
To be honest I'd break that single line into at least 2 if not 3 lines
anyway purely from a debug and maintenance point of view.
You are in real danger of turning Python into perl here! :-)

As to your error:

output.write(
          re.sub(
                r'([^\w\s])',
                lambda s: chr(int(s.group(),16))
                    ) % ord(s.group()),
                  line))

the parens dont seem to match up... Or am I miscounting?

Alan G




More information about the Tutor mailing list