How to convert escaped characters?

Viewed 23168

I want to convert strings containing escaped characters to their normal form, the same way Python's lexical parser does:

>>> escaped_str = 'One \\\'example\\\''
>>> print(escaped_str)
One \'Example\'
>>> normal_str = normalize_str(escaped_str)
>>> print(normal_str)
One 'Example'

Of course the boring way will be to replace all known escaped characters one by one: http://docs.python.org/reference/lexical_analysis.html#string-literals

How would you implement normalize_str() in the above code?

4 Answers

SingleNegationElimination already mentioned this, but here is an example:

In Python 3:

>>>escaped_str = 'One \\\'example\\\''
>>>print(escaped_str.encode('ascii', 'ignore').decode('unicode_escape'))
One 'example'
Related