How to un-escape a backslash-escaped string? [duplicate] Ask Question

How to un-escape a backslash-escaped string? [duplicate] Ask Question

Suppose I have a string which is a backslash-escaped version of another string. Is there an easy way, in Python, to unescape the string? I could, for example, do:

>>> escaped_str = '"Hello,\\nworld!"'
>>> raw_str = eval(escaped_str)
>>> print raw_str
Hello,
world!
>>> 

However that involves passing a (possibly untrusted) string to eval() which is a security risk. Is there a function in the standard lib which takes a string and produces a string with no security implications?

ベストアンサー1

>>> print '"Hello,\\nworld!"'.decode('string_escape')
"Hello,
world!"

おすすめ記事