Original: The Bytes/str dichotomy in Python 3Python 3 The most important new feature is probably a clearer distinction between text and binary data. Text is always Unicode, represented by the STR type, and binary data is represented by the bytes type. Python 3 does not mix str and bytes in any implicit way, which makes the distinction between them particularly clear. You cannot stitch strings and byte packets, search for strings in a byte packet (or vice versa), or pass a string into a function with a byte packet (or vice versa). It's a good thing. In any case, the line between the string and the byte packet is inevitable, and the following diagram is important to keep in mind: Enter image description Here strings can be encoded into byte packets, and byte packets can be decoded into strings. >>> ' €20 ' encode (' utf-8 ') b ' \xe2\x82\xac20 ' >>> B ' \xe2\x82\xac20 '. Decode (' utf-8 ') ' €20 ' This is the problem: strings are an abstract representation of text. Strings are composed of characters, and the characters are abstract entities that are not related to any particular binary representation. We live in the ignorance of happiness while manipulating strings. We can split and shard strings, and we can stitch and search strings. We don't care how they are represented internally, and each character in the string is saved in a few bytes. It is only when the strings are encoded into a byte package (for example, to send them on a channel) or decoded from a byte packet (reverse operation) that we begin to pay attention to this. The parameters passed in encode and decode are encoded (or codec). Encoding is a way of representing abstract characters in binary data. There are many kinds of coding at present. The UTF-8 given above is one of them, the following is another:>>> ' €20 '. Encode (' iso-8859-15 ') b ' \xa420 ' >>> B ' \xa420 '. Decode (' Iso-8859-15 ' €20 ' coding is a crucial part of this conversion process. Away from the code, Bytes object B ' \xa420 ' is just a bunch of bits. The encoding gives it meaning. With different encodings, the meaning of this heap of bits will vary greatly:>>> B ' \xa420 '. Decode (' windows-1255 ') '? 20 ' It is said that 80% of the money loss is due to the use of the wrong coding, so be careful. Reprint Address: https://www.cnblogs.com/txw1958/archive/2012/07/19/2598885.html
Small white Python road day1 Python3 's bytes/str