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.