Python Tip: Un-escaping strings

Recently at work a colleague asked me to help him solve the following problem:

I have a string that contains escaped characters, and I want to turn that into a string with those characters un-escaped. For example, it might contain '\"' as two separate characters.

For example, a test input string might be:

>>> test_input = r'Hello \"world\"'
>>> len(test_input)
>>> test_input[-1]
>>> test_input[-2]

As you can see, The back-slashes that are supposed to escape the quotes are separate characters. There are many naive solutions to this problem, and a surprisingly easy solution as well:

>>> test_input.decode("string_escape")
'Hello "world"'

The string_escape decoder is one of several "utility" decoders listed in the standard encodings list.

comments powered by Disqus