【问题标题】:python 3: can only concatenate str (not "bytes") to strpython 3:只能将str(不是“字节”)连接到str
【发布时间】:2021-03-11 09:59:30
【问题描述】:

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

我在这里遇到了一个错误,除了函数:

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

【问题讨论】:

  • 用您自己的话来说,您认为wrchar = c.encode('utf-8') 会做什么?为什么你的代码中有这一行?
  • @TheLazyScripter 我不认为这是一个很好的重复选择。它有点解释了这个问题;但在这种情况下,进行转换是合适的,而在这种情况下,删除不必要的转换更合适。

标签: python python-3.x string typeerror


【解决方案1】:

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

在 2.x 中,不使用任何 __future__ 声明,str 的类型与 bytes 相同,Unicode 文本(也称为 text)存储在 @ 987654325@ 个对象。

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

在 3.x 中,字符串可以正常工作。 str 是文本类型,存储 Unicode 代码点(not 与字符相同,顺便说一句),并且 notbytes 的别名。已经没有unicode了,但如果有的话,就和str一样了。

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

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-11-07
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 2020-10-20
  • 2019-05-13
  • 2021-02-22
相关资源
最近更新 更多