How do I un-escape a backslash-escaped string in Python?

PythonServer Side ProgrammingProgramming

There are two ways to go about unescaping backslash escaped strings in Python. First is using literal_eval to evaluate the string. Note that in this method you need to surround the string in another layer of quotes. For example:

>>> import ast
>>> a = '"Hello,\
world"' >>> print ast.literal_eval(a) Hello, world

Another way is to use the decode('string_escape') method from the string class. For example,

>>> print "Hello,\
world".decode('string_escape') Hello, world
raja
Updated on 30-Sep-2019 07:12:07

Advertisements