1. 程式人生 > >【Python】TypeError: a bytes-like object is required, not 'str'

【Python】TypeError: a bytes-like object is required, not 'str'

1、報錯

自己python3.+,使用別人python2.的程式碼報錯:

rs = pow(int(binascii.hexlify(text), 16), int(pubKey, 16), int(modulus, 16))
TypeError: a bytes-like object is required, not 'str'

2、原因

因為python3是bytes-like的,只能把它轉為str

3、解決

  # bytes object
  b = b"example"

  # str object
  s = "example"

  # str to bytes
  bytes(s, encoding = "utf8")

  # bytes to str
  str(b, encoding = "utf-8")

  # an alternative method
  # str to bytes
  str.encode(s)

  # bytes to str
  bytes.decode(b)

4、參考