【问题标题】:Python - a bytes like object is required, not strPython - 需要像对象这样的字节,而不是 str
【发布时间】:2015-06-21 00:28:02
【问题描述】:

我正在将我的 Twitch 机器人从 Python 2.7 迁移到 Python 3.5。我不断收到错误: a bytes like object is required not 'str' 在下面代码的第 2 行。

twitchdata = irc.recv(1204)
    data = twitchdata.split(":")[1]
    twitchuser = data.split("!")[0]
    twitchmsg = twitchdata.split(":")[2]
    chat = str(twitchuser) +": "+ str(twitchmsg)
    print(chat) #prints chat to console

【问题讨论】:

标签: python python-3.x irc twitch


【解决方案1】:

试试

data = twitchdata.decode().split(":")[1]

而不是

data = twitchdata.split(":")[1]

【讨论】:

  • 我想你的意思是decode。当然,其他split 调用也需要同样的方法,因此解码应该在第一行进行一次。再加上 ASCII 是否是正确编码的问题......
  • 我认为只是 decode() 并且我认为与docs.python.org/release/3.0.1/whatsnew/…有关
  • 谢谢。我使用 data = twitchdata.decode("ascii").split(":")[1] 并且有效
  • 没有ascii会更好,它会让你的代码从unicode问题中解脱出来
  • 我已经用 bytes(my_str, encoding='UTF-8') 解决了同样的问题,并删除了为 PY2 兼容性而留下的所有内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2017-03-05
  • 2016-11-27
  • 1970-01-01
相关资源
最近更新 更多