Python strings and str() method encoding and decoding

喜夏-厌秋 提交于 2019-12-06 11:04:20

This is only the case in Python 2. The existence of a decode method on Python 2's strings is a wart, which has been changed in Python 3 (where the equivalent, bytes, has only decode).

You can't 'encode' an already-encoded string. What happens when you do call encode on a str is that Python implicitly calls decode on it using the default encoding, which is usually ASCII. This is almost always not what you want. You should always call decode to convert a str to unicode before converting it to a different encoding.

(And decoded strings are unicode, and they do have type <unicode>, so I don't know what you mean by that question.)

In Python 3 of course strings are unicode by default. You can only encode them to bytes - which, as I mention above, can only be decoded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!