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

2024-09-29 19:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从Python2更新我的代码,我得到了一个以前在该版本中有效的错误。我迷路了,请帮帮我

我在except函数中遇到一个错误:

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

Tags: textinindex错误exceptionfindcantc
1条回答
网友
1楼 · 发布于 2024-09-29 19:32:25

I'm updating my code from python 2

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

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

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

因此,现在进行此编码步骤不仅没有必要,而且是一个bug。因此,您需要做的是删除它,并将c直接插入到输出字符串中

在我们进行现代化的同时,让我们用现代化的方式来组装绳子

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

相关问题 更多 >

    热门问题