python - 无法将字节连接到 str(转换为 Python3)

标签 python python-3.x

我正在尝试将我的 Python 2 代码转换为 Python3,但我收到以下错误:

Traceback (most recent call last):
  File "markovtest.py", line 73, in <module>
    get_all_tweets("quit_cryan")
  File "markovtest.py", line 41, in get_all_tweets
    outtweets = [(tweet.text.encode("utf-8") + str(b" ")) for tweet in alltweets]
  File "markovtest.py", line 41, in <listcomp>
    outtweets = [(tweet.text.encode("utf-8") + str(b" ")) for tweet in alltweets]
TypeError: can't concat bytes to str

问题出在这个for循环中:

outtweets = [(tweet.text.encode("utf-8") + " ") for tweet in alltweets]

我曾尝试将编码更改为解码或完全删除编码参数,但我无法弄清楚。任何帮助将不胜感激。

最佳答案

Python3 有几种不同的“字符串”类型。可以找到关于有哪些以及它们应该做什么的详细信息 here .

您正在尝试将一个字节字符串(基本上是一个不可变的字符数组)组合成一个 unicode 字符串。这不能(轻易)完成。

您的代码片段中的问题是推文文本(很可能是字符串)使用 encode 方法转换为字节。这工作正常,但是当您尝试将空格 "" (它是一个字符串)连接到字节对象时,会发生错误。您可以删除 encode 并将连接作为字符串(并可能稍后进行编码),或者通过在引号前添加 'b' 来使空间成为字节对象,例如 b"".

让我们看看您的选择:

In [1]: type("foo")
Out[1]: str

In [2]: type("foo".encode("utf-8"))
Out[2]: bytes

In [3]: "foo" + " "  # str + str
Out[3]: 'foo '

In [4]: "foo".encode("utf-8") + " "  # str + bytes
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-5c7b745d9739> in <module>()
----> 1 "foo".encode("utf-8") + " "

TypeError: can't concat bytes to str

我想对于你的问题,最简单的解决方案是将空格设为字节字符串(如下所示)。我希望这会有所帮助。

In [5]: "foo".encode("utf-8") + b" "  # bytes + bytes
Out[5]: b'foo '

关于python - 无法将字节连接到 str(转换为 Python3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46259640/

相关文章:

python - 从 TreeModel 中选定的索引检索特定数据

python - 未绑定(bind)本地错误: local variable <var> referenced before assignment

python - PuTTY Windows pywinauto 背景

没有 ascii 编码和 b 前缀的 Python3 : Is there a way to use telnetlib like in python2,?

python - 与多级索引数据帧一起使用时 pd.DataFrame.drop 的意外行为

Python 的新 `functools.cached_property` 错误或限制?

python - &符号在打印功能中如何工作?

python - conda 错误 : Cannot link a source that does not exist

python - 重新流式传输另一个 nginx rtmp 流

javascript - PhantomJS 的行为不同于 Firefox webdriver