and type bytes encoding conversion method python

A, bytes type

is a collection of bytes pile type byte string type in python are bytes beginning at b. E.g:

>>> a = "中国"
>>> a.encode("utf-8")
b ' \ xe4 \ xb8 \ limits \ xe5 \ x9b \ xbd '

py3 string are Unicode encoding, the character normal display, the remaining coded data type are displayed in bytes.

bytes type of action:

The computer can store binary, our characters, pictures, videos, music and want to save to your hard drive, it must be the right way and then encoded into binary memory.

For text, we can gbk coding, it can also be utf-8, ASCII encoding.

For images, it must be encoded as a PNG, JPEG and other formats

For music to be encoded into MP3, WAV and so on ...

In python, converted into the binary data is not directly represented in the form of 0101010, but with the called bytes (bytes) type, where the hexadecimal byte binary representation, i.e., a 16 four hexadecimal binary, representative of a two-byte hexadecimal.

Can be written to disk in the python, the string must be encoded into bytes. If not encoded header statement, python3 default file store encoded with utf-8.

Further, Python, the character encoding e.g. gbk, utf-8, ASCII and the like may also identify the conversion, while images, music, video, encoding can not be identified, appears only in the form of bytes, transmission and storage.

Two, python encoding conversion method

Conversion encoding refers to encoding transformed into another code, such as utf-8 to gbk.

Transcoding role:

Different operating system encoding, utf-8 can not look directly at the win, because the windows are encoded by GBK, it was turned into gbk.

If you turn the normal display with the GBK character on Linux \ Mac, you have to turn into utf-8 encoding.

Transcoding method:

decode () decode, encode () encoding

UTF-8 -> decode decoding -> the Unicode
Unicode -> encode coding -> GBK / UTF-8

E.g:

>>> a = "中国"
>>> b = a.encode("utf-8")
>>> print(b)
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> b.decode("utf-8")
'中国'

Note: In what coding, it is necessary to decode what, or else an error or garbled

Guess you like

Origin www.cnblogs.com/relex/p/11008873.html