python比较"\n"转义字符和"\\n

4 投票
1 回答
11943 浏览
提问于 2025-04-18 07:13

好的,

我有两个字符串,"Hello\nWorld!"Hello\\nWorld!。我需要比较这两个字符串,让 \n\\n 被视为相等。

这其实不难。我只需要用 string1.replace("\n", "\\n") 就可以了。

但是,如果我需要对所有的转义字符,包括unicode转义字符,都这样处理,那手动替换就不太行了。

更新

举个例子:

我从文件中读取到 Hello\nWorld!(在编辑器中打开文件时看到的样子)。而Python会看到 Hello\\nWorld!

我想把最后一个和第一个进行比较,让它们被视为相等。

1 个回答

10

你觉得用 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

撰写回答