python 将 "\n"转义字符与 "\\n"进行比较

标签 python string replace escaping backslash

好的,

我有两个字符串,"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/

相关文章:

c - 从文件中读取分号分隔的字符串

java - 替换java中字符串的一部分

javascript - 如何使用 .replace with match() 方法 javaScript

jquery - 添加到内联 html 样式属性的函数在 IE 中不起作用

python - 在 hackerrank 竞赛中导入 numpy

Python父类访问子类的类变量

python - Openpyxl:如何在检查单元格是否包含特定值后复制一行

C++:使用sizeof的char数组的大小

python - 用 html 实体替换重音字符

python - pdf文件中的Scrapy抓取数据