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
相关产品推荐
相关产品推荐

