You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python2迁移至Python3报错:can only concatenate str (not "bytes") to str

解决Python3迁移中字符串与字节拼接的TypeError问题

嘿,我刚看完你的问题,这是Python2转Python3时非常典型的类型兼容问题——毕竟Python3把字符串(str)和字节序列(bytes)严格分开了,不像Python2那样混着用。

为啥会报错?

你看这段触发问题的代码:

wrchar = c.encode('utf-8')
raise Exception("Can't find char '" + wrchar + "' of text in alphabet!")

在Python3里,遍历text得到的c是Unicode字符串,调用encode('utf-8')后会生成bytes对象。而Python3不允许直接把字符串和字节类型拼接,所以就抛出了那个TypeError: can only concatenate str (not "bytes") to str。

怎么修复?

有两种简单的办法,挑你顺手的来:

方法1:直接用原字符(最省事)

其实c本身就是字符串,完全没必要编码成bytes,直接用它就行:

except ValueError as e:
    raise Exception(f"Can't find char '{c}' of text in alphabet!")

方法2:把bytes转回字符串

如果确实需要保留编码后的表示(比如特殊字符的字节形式),那就把bytes再解码回str:

except ValueError as e:
    wrchar_str = c.encode('utf-8').decode('utf-8')
    raise Exception("Can't find char '" + wrchar_str + "' of text in alphabet!")

或者用Python3的f-string让代码更简洁易读:

except ValueError as e:
    wrchar_str = c.encode('utf-8').decode('utf-8')
    raise Exception(f"Can't find char '{wrchar_str}' of text in alphabet!")

小建议

另外,Python3里尽量用更具体的异常类型(比如自定义一个AlphabetNotFoundError),而不是直接抛出通用的Exception,不过这属于优化项,先解决当前的报错更重要~

内容的提问来源于stack exchange,提问作者Luxe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:28:52