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 proc
The ast.literal_eval function comes close, but it will expect the string to be properly quoted first.
Of course Python's interpretation of backslash escapes depends on how the string is quoted (""
vs r""
vs u""
, triple quotes, etc) so you may want to wrap the user input in suitable quotes and pass to literal_eval
. Wrapping it in quotes will also prevent literal_eval
from returning a number, tuple, dictionary, etc.
Things still might get tricky if the user types unquoted quotes of the type you intend to wrap around the string.