python比较“\n”转义字符与“\\n”

2024-06-16 12:48:12 发布

您现在位置:Python中文网/ 问答频道 /正文

好的

我有两个字符串,"Hello\nWorld!"Hello\\nWorld!。我必须比较那些\n\\n相等的方法。

这不难。我只是string1.replace("\n", "\\n")

但是如果我必须对所有转义字符(包括unicode转义)正确地执行此操作,那么手动替换不是一个选项。

更新

示例案例:

我从文件Hello\nWorld!中读取(在编辑器中打开文件时可以看到)。Python将看到Hello\\nWorld!

我想把最后一个和第一个比较,它们是相等的。


Tags: 文件方法字符串示例hello选项unicode手动
1条回答
网友
1楼 · 发布于 2024-06-16 12:48:12

使用^{}编码怎么样?

>>> 'hello\r\n'.encode('unicode_escape') == 'hello\\r\\n'
True
>>> 'hello\r\n' == 'hello\\r\\n'.decode('unicode_escape')
True

在Python3.x中,需要对字符串/字节进行编码/解码:

>>> 'hello\r\n'.encode('unicode_escape').decode() == 'hello\\r\\n'
True
>>> 'hello\r\n' == 'hello\\r\\n'.encode().decode('unicode_escape')
True

相关问题 更多 >