AttributeError: 'str' object has no attribute 'decode' in Python
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 ™ 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.
-
Đ0
Đà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 ™ will sell for → Aisa ™ 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 bytesmy_msg = 'FTM ™ will sell for → Aisa ™ 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 variablemy_msg = b'FTM ™ will sell for → Aisa ™ company' decoded_msg = my_msg.decode('utf-8') print(decoded_msg)
All solutions have same the result. Hope this answer will helpful to you.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.