Process escape sequences in a string in Python

前端 未结 6 1262
隐瞒了意图╮
隐瞒了意图╮ 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 05:01

    The correct thing to do is use the 'string-escape' code to decode the string.

    >>> myString = "spam\\neggs"
    >>> decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3 
    >>> decoded_string = myString.decode('string_escape') # python2
    >>> print(decoded_string)
    spam
    eggs
    

    Don't use the AST or eval. Using the string codecs is much safer.

提交回复
热议问题