Reputation: 10892
In Python, there is an encode
method in unicode strings to encode from unicode to byte string. There is a decode
method in string to do the reverse.
But I'm confused what the encode
method in string for?
Upvotes: 6
Views: 3424
Reputation: 799180
It's useful for non-text codecs.
>>> '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'
Upvotes: 10
Reputation: 2145
It first decodes to Unicode using the default encoding, then encodes back to a byte string.
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> sys.setdefaultencoding('latin-1')
>>> '\xc4'.encode('utf-8')
'\xc3\x84'
Here, '\xc4'
is Latin-1 for Ä and '\xc3\x84'
is UTF-8 for Ä.
Upvotes: 5