繁体   English   中英

python 3:只能将 str(不是“字节”)连接到 str

[英]python 3: can only concatenate str (not “bytes”) to str

我正在从 python 2 更新我的代码,但我遇到了以前在该版本中有效的错误。 我很迷茫,请帮助。

除了 function 之外,我在这里遇到错误:

for c in text:
  try:
      if isEncrypt:
          i = tp_alphabet.index(c)
          ret += tc_alphabet[i]
       else:
          i = tc_alphabet.index(c)
          ret += tp_alphabet[i]
   except ValueError as e:
          wrchar = c.encode('utf-8')
          raise Exception("Can't find char '" + wrchar + "' of text in alphabet!")

当我运行这个:

dec = machine.decrypt(plaintext)
print(dec)

这是错误:

File "python3.py", line 133, in __encDec
    raise Exception("Can't find char '" + wrchar + "' of text in alphabet!")
TypeError: can only concatenate str (not "bytes") to str

我正在从 python 2 更新我的代码

在 2.x 中,不使用任何__future__声明,类型strbytes相同,并且 Unicode 文本(也称为text )存储在unicode对象中。

据推测, text (因此还有c )在 2.x 版本的代码中属于unicode类型,而普通字符串文字(例如"Can't find char '" )是str (即bytes )对象。 因此需要进行转换:将 Unicode 数据编码为字节,然后连接在一起 - 即代码行wrchar = c.encode('utf-8')

在 3.x 中,字符串可以正常工作。 str是文本类型,存储 Unicode 代码点(字符不同,顺便说一句),并且不是bytes的别名。 不再有unicode ,但如果有,它将与str相同。

因此,现在不仅没有必要,而且执行此编码步骤是一个错误。 所以你需要做的是删除它,然后将c直接插入到 output 字符串中。

在我们进行现代化改造的同时,让我们以现代方式组装琴弦。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM