【问题标题】:How can this simple Python 2 code be translated to Python 3? [Python Student]如何将这个简单的 Python 2 代码翻译成 Python 3? [Python学生]
【发布时间】:2017-03-25 06:16:49
【问题描述】:

这篇文章的答案,https://stackoverflow.com/a/16175368/6448312 在 Python 3 上无法为我运行。我收到错误 -

#$>test2.py Traceback (most recent call last):   File "C:\Users\.\OneDrive\PROJECTS for fun\smartApp\test2.py", line 4, in <module>
for row in output.split('\n'): TypeError: a bytes-like object is required, not 'str'

我使用的是他们发布的相同代码 - https://hastebin.com/ubafadikos.py

似乎我需要将字符串转换为字节类型,我尝试过使用 newOutput = bytes(output, 'utf-8') 但这也失败了,并显示了

的错误消息
newOutput = bytes(output, 'utf-8')
TypeError: str() takes at most 1 argument (2 given)

我不知道接下来要尝试什么 :( 我使用的是 Python 3.6.1,在 Python 2.7 上运行代码可以正常工作。

编辑:使用 newOutput = bytes(output) 有效

【问题讨论】:

  • 您的第一条错误消息看起来像 Python 3 错误消息,但您的第二条错误消息看起来像 Python 2 错误消息。你运行这段代码的方式真的很奇怪。
  • @user2357112 感谢您的评论,两个输出都来自 Python3。我取出了第二个参数,因为它说 newOutput = bytes(output, 'utf-8') 不希望超过 1 并且代码运行成功。但是我不确定这在语法上是否正确。

标签: python python-2.7 python-3.x


【解决方案1】:

试试for row in output.decode().split('\n')

Source

【讨论】:

  • 太棒了,谢谢。我真的希望他们可以在 Python 错误消息中添加一些提示来指出这样的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 2017-11-04
  • 1970-01-01
  • 2013-11-25
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多