Search code examples
python-3.xsystemmessageattributeerrorencoder

Why is this error appearing?


AttributeError: 'builtin_function_or_method' object has no attribute 'encode'

I'm trying to make a text to code converter as an example for an assignment and this is some code based off of some I found in my research,

import binascii

text = input('Message Input: ')

data = binascii.b2a_base64.encode(text)
text = binascii.a2b_base64.encode(data)
print (text), "<=>", repr(data)

data = binascii.b2a_uu(text)
text = binascii.a2b_uu(data)
print (text), "<=>", repr(data)

data = binascii.b2a_hqx(text)
text = binascii.a2b_hqx(data)
print (text), "<=>", repr(data)

can anyone help me get it working? it's supposed to take an input in and then convert it into hex and others and display those... I am using Python 3.6 but I am also a little out of practice...


Solution

  • TL;DR:

    data = binascii.b2a_base64(text.encode())
    text = binascii.a2b_base64(data).decode()
    print (text, "<=>", repr(data))
    

    You've hit on a common problem in the Python3 - str object vs bytes object. The bytes object contains sequence of bytes. One byte can contain any number from 0 to 255. Usually those number are translated through the ASCII table into a characters like english letters. Usually in the Python you should use bytes for working with binary data.

    On the other hand the str object contains sequence of code points. One code point usually represent one character printed on your screen when you call print. Internally it is sequence of bytes so the Chinese symbol is internally saved as 3 bytes long sequence.

    Now to the your problem. The function requires as input the bytes object but you've got a str object from the function input. To convert str into bytes you have to call str.encode() method on the str object.

    data = binascii.b2a_base64(text.encode())
    

    Your original call binascii.b2a_base64.encode(text) means call method encode of the object binascii.b2a_base64 with parameter text.

    The function binascii.b2a_base64 returns bytes contains original input encoded with the base64 algorithms. Now to get back the original str from encoded data you have to call this:

    # Take base64 encoded data and return it decoded as bytes object
    decoded_data = binascii.a2b_base64(data) 
    # Convert bytes object into str
    text = decoded_data.decode()
    

    It can be written as one line

    decoded_data = binascii.a2b_base64(data).decode()
    

    WARNING: Your call of print is invalid for Python 3 (it will work only in the python console)