Process escape sequences in a string in Python
escaping, python, string
Solution
The correct thing to do is use the 'string-escape' code to decode the string.
>>> myString = "spam\\neggs"
>>> decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3
>>> decoded_string = myString.decode('string_escape') # python2
>>> print(decoded_string)
spam
eggs
Don't use the AST or eval. Using the string codecs is much safer.
Problem
Sometimes when I get input from a file or the user, I get a string with escape sequences in it. I would like to process the escape sequences in the same way that Python processes escape sequences in string literals. For example, let's say `myString` is defined as: ``` >>> myString = "spam\\neggs" >>> print(myString) spam\neggs ``` I want a function (I'll call it `process`) that does this: ``` >>> print(process(myString)) spam eggs ``` It's important that the function can process all of the escape sequences in Python (listed in a table in the link above). Does Python have a function to do this?
Related problems
- How to fix "SyntaxWarning: invalid escape sequence" in Python?
- Using python's eval() vs. ast.literal_eval()
- How to un-escape a backslash-escaped string?
- How do I .decode('string-escape') in Python 3?
- How can I convert special characters in a string back into escape sequences?
- Reversing Python's re.escape
- Convert "\x" escaped string into readable string in python