jeudi 26 mars 2015

How to convert a string representation of unicode literals from a file, into real unicode literals using python 3?

I got a file with plain text and some representation of unicode literals such as



STRING_LITERAL2 = '"' ( ([^\x22\x5C\xA\xD]) | '\' [tbnrf\"'] )* '"'


I need to interpret these representations into real literals and use them in a regular expression. The problem is, if I simple read them, I get



str_lit2 = ('\'"\' ( ([^\\x22\\x5C\\xA\\xD]) | \'\\\' [tbnrf\\"\'] )* \'"\''


and the import.re package of python can't interpret these literals.


I can find the specific representations using re.sub("\\\\x",...) but if I want to replace them re.sub("\\\\x","\\x".encode().decode('unicode_escape'), str_lit2) - to say these are real literals - I get the following error:



UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape


So how can I convert these string representatives of unicode literals into real literals? Of course only for python3, because I need to use this.


Greetings Meldamos


Aucun commentaire:

Enregistrer un commentaire