AttributeError: 'str' object has no attribute 'decode' in Python

Dung Do Tien Jun 02 2022 210

 Hello, I have a small problem with Python 3. I have a string text that contains some Unicode symbol, I want to decode it before displaying it.  I was trying to use decode() method, I follow a video on the internet, sample like this:

 my_msg = 'FTM ™ will sell for → Aisa &#8482 company' 

# ⛔️ AttributeError: 'str' object has no attribute 'decode'. Why decode() method does not exist?
decoded_msg = my_msg.decode('utf-8')
print(decoded_msg)

But when this code is running, I got an exception AttributeError: 'str' object has no attribute 'decode'.

 Traceback (most recent call last):
  File "main.py", line 4, in <module>
    decoded_msg = my_msg.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'

Anyone can explain and help me solve this issue? The decode() is a built-in function, so I still don't know why it occurs.

Thank you in advance.

Have 1 answer(s) found.
  • Đ

    Đàm Ngọc Sơn Jun 02 2022

    Right, decode() method is a built-in function in Python. But it only accepts input as a bytes datatype.  So you can refer to some solutions below:

    Solution 1: Convert string to bytes before decode

     my_msg = 'FTM &#8482; will sell for &#8594; Aisa &#8482 company' 
    
    encode_msg = bytes(my_msg, encoding='utf-8')
    decoded_msg = encode_msg.decode('utf-8')
    
    print(decoded_msg)

    Solution 2: Use encode() method to help convert strings to bytes

     my_msg = 'FTM &#8482; will sell for &#8594; Aisa &#8482 company' 
    
    encode_msg = my_msg.encode('utf-8')
    decoded_msg = encode_msg.decode('utf-8')
    
    print(decoded_msg)

    Solution 3: Add b character before your string variable

     my_msg = b'FTM &#8482; will sell for &#8594; Aisa &#8482 company' 
    
    decoded_msg = my_msg.decode('utf-8')
    
    print(decoded_msg)

    All solutions have same the result. Hope this answer will helpful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close