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

Roel Schroeven roel at roelschroeven.net
Wed Dec 7 03:42:18 EST 2022



Op 7/12/2022 om 4:37 schreef Jach Feng:
> 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
You missed a pair of quotes. They are easily overlooked but very 
important. The point is to wrap your string in another pair of quotes so 
it becomes a valid Python string literal in a Python string which can 
then be passed to ast.literal_eval(). Works for me:

In [7]: s0 = r'\x0a'

In [8]: import ast

In [9]: ast.literal_eval('"%s"' % s0)
Out[9]: '\n'

-- 
"Experience is that marvelous thing that enables you to recognize a
mistake when you make it again."
         -- Franklin P. Jones



More information about the Python-list mailing list