Han*_*ila 3 python string replace escaping backslash
好,
我有两个字符串,"Hello\nWorld!"和Hello\\nWorld!.我必须比较那些\n和\\n平等的方式.
多数民众赞成并不难.我只是string1.replace("\n", "\\n").
但是,如果我必须正确执行包括unicode转义在内的所有转义字符,那么手动替换不是一种选择.
UPDATE
Exaple案例:
我从文件中读取Hello\nWorld!(如在编辑器中打开文件时所见).Python会看到Hello\\nWorld!
我想比较最后一个与第一个相同的方式.
fal*_*tru 10
如何使用unicode_escape编码?
>>> 'hello\r\n'.encode('unicode_escape') == 'hello\\r\\n'
True
>>> 'hello\r\n' == 'hello\\r\\n'.decode('unicode_escape')
True
Run Code Online (Sandbox Code Playgroud)
在Python 3.x中,您需要对字符串/字节进行编码/解码:
>>> 'hello\r\n'.encode('unicode_escape').decode() == 'hello\\r\\n'
True
>>> 'hello\r\n' == 'hello\\r\\n'.encode().decode('unicode_escape')
True
Run Code Online (Sandbox Code Playgroud)