无法将字节连接到 str(转换为 Python3) [英] Can't concat bytes to str (Converting to Python3)

查看:108
本文介绍了无法将字节连接到 str(转换为 Python3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to convert my Python 2 code to Python3 but I am receiving the following error:

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 循环:

The problem is in this for loop:

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

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

I have tried changing encode to decode or removing the encode parameter altogether but I cannot figure it out. Any help would be appreciated.

推荐答案

Python3 有几种不同的字符串"类型.可以在此处找到有关有哪些以及它们应该做什么的详细信息.

Python3 has several different 'string' types. Details on which ones there are and what they are supposed to do can be found here.

您正在尝试将字节字符串(基本上是不可变的字符数组)组合为 unicode 字符串.这不能(很容易)做到.

You are trying to combine a bytes string (basically an immutable character array) to a unicode string. This can not (easily) be done.

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

The problem in your code snippet is that the tweet text, most likely a string, is converted to bytes with the encode method. This works fine, but when you try to concatenate the space " " (which is a string) to the bytes object the error occurs. You can either remove the encode and do the concatenation as strings (and maybe encode later) or make the space a bytes object by adding a 'b' before the quotes like this 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

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

I guess for you problem, the simplest solution would be to make the space a byte string (as below). I hope this helps.

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

这篇关于无法将字节连接到 str(转换为 Python3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆