有时当我从文件或用户获取输入时,我会得到一个包含转义序列的字符串。我想处理转义序列 in the same way that Python processes escape sequences in string literals .
例如,假设 myString
定义为:
>>> myString = "spam\\neggs"
>>> print(myString)
spam\neggs
我想要一个执行此操作的函数(我将其称为 process
):
>>> print(process(myString))
spam
eggs
该函数可以处理 Python 中的所有转义序列,这一点很重要(在上面链接的表格中列出)。
Python 有这样的功能吗?
最佳答案
正确的做法是使用“字符串转义”代码来解码字符串。
>>> 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
不要使用 AST 或 eval。使用字符串编解码器更安全。
关于python - 在 Python 中处理字符串中的转义序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020539/