How to reverse re.escape? This blog from 2007 says there is no reverse function, but is that still true, ten years later?
Python 2's decode('string_escape')
doesn't work on all escaped chars (such as space).
>>> re.escape(' ')
'\\ '
>>> re.escape(' ').decode('string-escape')
'\\ '
Python 3: Some suggest unicode_escape
or codec.escape_decode
or ast.literal_eval
but no luck with spaces.
>>> re.escape(b' ')
b'\\ '
>>> re.escape(b' ').decode('unicode_escape')
'\\ '
>>> codecs.escape_decode(re.escape(b' '))
(b'\\ ', 2)
>>> ast.literal_eval(re.escape(b' '))
ValueError: malformed node or string: b'\\ '
So is this really the only thing that works?
>>> re.sub(r'\\(.)', r'\1', re.escape(' '))
' '