【Python】AttributeError: ‘str‘ object has no attribute ‘decode‘

created at 12-24-2021 views: 100

cause of the problem

There are two reasons:

  • The difference between Python2 and Python3 in string encoding.
  • Inconsistent encoding and decoding types

encode and decode

str and bytes represent two data types, 

  • stris a string type, and bytes is a byte type. 
  • encode str to get bytes, and decode bytes to get str. 

The two are mutually converted. One of the reasons for the above problem is the use of decoding on the str string, which is obviously the pig's head and the horse's tail.

txt ='Hello, shiyi, thank you very much for staying with me.'
#str->bytes encode
txt = txt.encode('utf-8')
#bytes->str decode
txt = txt.decode('utf-8')

# results
Process finished with exit code 0

Coding method of python2 and python3

  • Python3's str is not bytes by default, so you can't decode, you can only convert encode to bytes, and then decode.
  • The default str of python2 is bytes, so it can decode


  • For the first reason: delete decode('utf-8') or use 'str'.encode('utf-8'). decode('utf-8') first encode into bytes, then Decode into string.
  • For the second type: various encoding methods try to solve: utf-8,gbk,ISO-8859-1
created at:12-24-2021
edited at: 12-27-2021: