Python 字符串编码方法

6 投票
2 回答
3402 浏览
提问于 2025-04-16 12:53

在Python中,unicode字符串有一个叫做encode的方法,用来把unicode转换成字节串。而字符串中有一个decode的方法,可以做相反的操作,把字节串转换回unicode。

不过我有点困惑,字符串中的encode方法是用来干嘛的呢?

2 个回答

5

它首先使用默认的编码方式解码成Unicode,然后再编码回字节字符串。

>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> sys.setdefaultencoding('latin-1')
>>> '\xc4'.encode('utf-8')
'\xc3\x84'

在这里,'\xc4' 是拉丁-1编码表示的Ä,而'\xc3\x84' 是UTF-8编码表示的Ä。

10

这对于非文本编码器很有用。

>>> 'Hello, world!'.encode('hex')
'48656c6c6f2c20776f726c6421'
>>> 'Hello, world!'.encode('base64')
'SGVsbG8sIHdvcmxkIQ==\n'
>>> 'Hello, world!'.encode('zlib')
'x\x9c\xf3H\xcd\xc9\xc9\xd7Q(\xcf/\xcaIQ\x04\x00 ^\x04\x8a'

撰写回答