The distinction between bytes and STR in Python 3

Source: Internet
Author: User

The recent conversion of a piece of py2 code to the PY3 code, the result of running to the socket to write data in the code part of the ' STR ' does not support the buffer interface such a mistake.

After a search, it was found that Py3 was strictly distinguished from Str and bytes. How do you understand str and bytes? You can think of Str as a piece of text, like "abcd#%$^*&" or something, and bytes, a bunch of binary 0, 1 of bits. Look at the following figure:

You can see that the type of STR is class ' str ', and Str.encode () after the type is class ' bytes ', which is different. and Str.encode (' GBK ') and Str.encode (' Utf-8 ') The representation of the bytes is also different. That is, when different encodings are used, the same text, "haha", is not the same as the heap 01 in memory.

Between str and bytes can be transformed by encode (), decode ().

Here is a piece of code in python34\lib\socket.py, you can see in Py3, write to a socket file must write the bytes or bytearray type of

1    defWrite (self, b):2         """Write the given bytes or ByteArray object *b* to the socket3 and return the number of bytes written. This can is less than4 Len (b) If not all data could is written. If the socket is5 non-blocking and no bytes could be written None are returned.6         """7 self._checkclosed ()8 self._checkwritable ()9         Try:Ten             returnSelf._sock.send (b) One         excepterror as E: A             #XXX What about EINTR? -             ifE.args[0]inch_blocking_errnos: -                 returnNone the             Raise

Therefore, if the content type is not bytes or bytearray but Str at the time of the Send (content), the problem of ' STR ' does not support the buffer interface will appear. will Send ( Content) fixed to send (Content.encode ()) just fine.

The distinction between bytes and STR in Python 3

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.