有时当我从文件或用户那里获得输入时,我会得到一个包含转义序列的字符串.我想以与Python处理字符串文字中的转义序列相同的方式处理转义序列.
例如,假设myString定义为:
>>> myString = "spam\\neggs"
>>> print(myString)
spam\neggs
Run Code Online (Sandbox Code Playgroud)
我想要一个函数(我会称之为process)这样做:
>>> print(process(myString))
spam
eggs
Run Code Online (Sandbox Code Playgroud)
重要的是该函数可以处理Python中的所有转义序列(在上面链接的表中列出).
Python有功能吗?
如果我有一个字符串(0x61 0x62 0xD),repr该字符串的函数将返回'ab\r'.
有没有办法进行反向操作:如果我有字符串'ab\r'(带字符0x61 0x62 0x5C 0x72),我需要获取字符串0x61 0x62 0xD.
我已经检查了此解决方案,但在python3中不起作用。
我有一个这样的转义字符串:str = "Hello\\nWorld"而且我想获得未转义的相同字符串:str_out = Hello\nWorld
我尝试了这个没有成功: AttributeError: 'str' object has no attribute 'decode'
这是我的示例代码:
str = "Hello\\nWorld"
str.decode('unicode_escape')
Run Code Online (Sandbox Code Playgroud)