cristina parker
cristina parker

Reputation: 95

How do I fix AttributeError: 'bytes' object has no attribute 'encode'?

This is my code z = (priv.to_string().encode('hex')) and I got this error:

"AttributeError: 'bytes' object has no attribute 'encode'"

looks like I missed something to show "encode" after the code:

z = (priv.to_string().

Upvotes: 7

Views: 39047

Answers (2)

jcomeau_ictx
jcomeau_ictx

Reputation: 38442

on Python3 systems older than version 3.5, you can from binascii import hexlify and use hexlify(priv.to_string())

Upvotes: 2

glhr
glhr

Reputation: 4537

Two problems here:

  • you're using priv.to_string() (which isn't a built-in method) instead of str(priv)
  • 'hex' has been removed as an encoding in Python 3, so with str(priv).encode('hex') you'll get the following error: LookupError: 'hex' is not a text encoding; use codecs.encode()to handle arbitrary codecs

However, since Python 3.5, you can simply do:

priv.hex()

with priv being a byte string.

Example:

priv = b'test'
print(priv.hex())

Output:

74657374

Upvotes: 12

Related Questions