【问题标题】:python compare "\n" escape chars with "\\n"python将“\n”转义字符与“\\n”进行比较
【发布时间】:2014-05-21 15:46:34
【问题描述】:

好的,

我有两个字符串,"Hello\nWorld!"Hello\\nWorld!。我必须以\n\\n 等于的方式进行比较。

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

但是,如果我必须为所有转义字符(包括 unicode 转义)正确处理,那么手动替换不是一种选择。

更新

示例:

我从文件Hello\nWorld! 中读取(如在编辑器中打开文件时所见)。 Python 会看到Hello\\nWorld!

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

【问题讨论】:

  • 这里更大的背景是什么?您是在谈论打印字符串与其repr() 之间的区别吗?或者字节字符串 ('foo') 和 unicode 字符串 (u'foo') 之间的区别?还是这些字符串来自已经转义的外部来源?
  • \x 不是 unicode 转义,这是显示不可打印 bytes 的方式。您需要展示一些示例输入。
  • X 是一个示例字符(任何字符)。已编辑,希望现在更清楚。

标签: python string replace escaping backslash


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2014-03-05
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多