好的,
我有两个字符串,"Hello\nWorld!"
和 Hello\\nWorld!
。我必须比较那些 \n
和 \\n
相等的方式。
这并不难。我只是 string1.replace("\n", "\\n")
。
但是,如果我必须对所有转义字符(包括 unicode 转义字符)执行正确操作,那么手动替换不是一个选项。
更新
案例:
我从文件 Hello\nWorld!
中读取(如在编辑器中打开文件时所见)。 Python 将看到 Hello\\nWorld!
我想比较最后一个和第一个相等的方式。
最佳答案
如何使用 unicode_escape
编码?
>>> 'hello\r\n'.encode('unicode_escape') == 'hello\\r\\n'
True
>>> 'hello\r\n' == 'hello\\r\\n'.decode('unicode_escape')
True
在 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
关于python 将 "\n"转义字符与 "\\n"进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23788038/