How to convert a raw string r'\xdd' to '\xdd' more gracefully?

Jach Feng jfong at ms4.hinet.net
Tue Dec 6 22:37:54 EST 2022


MRAB 在 2022年12月7日 星期三上午11:04:43 [UTC+8] 的信中寫道:
> On 2022-12-07 02:23, Jach Feng wrote: 
> > s0 = r'\x0a' 
> > At this moment it was done by 
> > 
> > def to1byte(matchobj): 
> > ....return chr(int('0x' + matchobj.group(1), 16)) 
> > s1 = re.sub(r'\\x([0-9a-fA-F]{2})', to1byte, s0) 
> > 
> > But, is it that difficult on doing this simple thing? 
> >
> You could try this: 
> 
> >>> s0 = r'\x0a' 
> >>> ast.literal_eval('"%s"' % s0) 
> '\n'
Not work in my system:-(

Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:08:11) [MSC v.1928 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s0 = r'\x0a'
>>> import ast
>>> ast.literal_eval("%s" % s0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Jach\AppData\Local\Programs\Python\Python38-32\lib\ast.py", line 59, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "C:\Users\Jach\AppData\Local\Programs\Python\Python38-32\lib\ast.py", line 47, in parse
    return compile(source, filename, mode, flags,
  File "<unknown>", line 1
    \x0a
       ^
SyntaxError: unexpected character after line continuation character


More information about the Python-list mailing list