【问题标题】:In Python3 the behaviour of the inbuilt repr() function has changed when compared to Python2在 Python3 中,与 Python2 相比,内置 repr() 函数的行为发生了变化
【发布时间】:2021-01-25 20:28:05
【问题描述】:

在 Python3 中,与 Python2 相比,内置 repr() 函数的行为发生了变化。

在python2中

repr("Дует Світязь")
"'\\xd0\\x94\\xd1\\x83\\xd0\\xb5\\xd1\\x82 \\xd0\\xa1\\xd0\\xb2\\xd1\\x96\\xd1\\x82\\xd1\\x8f\\xd0\\xb7\\xd1\\x8c'"

在 Python3 中

repr("Дует Світязь")
"'Дует Світязь'"

如何让 repr() 在 Python3 中像在 Python2 中一样工作,或者作为另一种将字符串转换为转义字符的方法 在我的代码中。我将查找表中的转义字符用于我的 LCD 显示转换例程。

平台是Raspberry Pi OS(Raspbian)。

我也尝试过使用 reprlib() 没有成功。它提供与 repr() 相同的输出。使用 string.encode 可以在某种程度上证明解决方案,但结果与 Python2 repr() 不同

txt = "Дует Світязь"
txt.encode('utf8')
b'\xd0\x94\xd1\x83\xd0\xb5\xd1\x82 \xd0\xa1\xd0\xb2\xd1\x96\xd1\x82\xd1\x8f\xd0\xb7\xd1\x8c'

【问题讨论】:

  • repr() 在 Python3 中的工作与在 Python2 中相同“ -​​ 我认为你不能。升级确实需要一些费用。

标签: python-3.x repr


【解决方案1】:

您可以将字符串编码为字节对象:

print('Дует Світязь'.encode('utf-8'))

打印:

b'\xd0\x94\xd1\x83\xd0\xb5\xd1\x82 \xd0\xa1\xd0\xb2\xd1\x96\xd1\x82\xd1\x8f\xd0\xb7\xd1\x8c'

编辑:

s = str('Дует Світязь'.encode('utf-8')).lstrip('b').replace('\\', r'\\')
print(s)

打印:

'\\xd0\\x94\\xd1\\x83\\xd0\\xb5\\xd1\\x82 \\xd0\\xa1\\xd0\\xb2\\xd1\\x96\\xd1\\x82\\xd1\\x8f\\xd0\\xb7\\xd1\\x8c'

【讨论】:

  • string.encode() 不幸的是没有给出与 repr() 相同的结果,这意味着修改我的翻译表中的一千多行,所以我很想让 repr() 工作与 Python2 相同。
  • @BobRathbone 查看我的编辑。这是你想要的结果吗?
  • 非常感谢。上面的方法解决了这个问题,但是 string.encode() 产生一个字节表示,repr() 产生一个 ascii 字符串字符串。但是我可能会找到解决方法。
【解决方案2】:

感谢 Andrej Kesely,他让我找到了正确的解决方案

在 Python2 中

s = repr(text)

在 Python3 中

s = str(text.encode('utf-8')).lstrip('b')

我真的不明白为什么 Python3 的作者觉得有必要改变诸如 repr() 之类的内置函数的工作方式。毫无疑问,他们有他们的理由。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 2018-03-15
    • 2017-04-26
    相关资源
    最近更新 更多