Process escape sequences in a string in Python

前端 未结 6 1250
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 03:56

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

6条回答
  •  礼貌的吻别
    2020-11-22 04:59

    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.

提交回复
热议问题