2512380815 发表于 2015-12-3 09:13:02

Python 3中bytes和str的分别

  最近把一段py2的代码转换到py3的代码,结果运行到向socket中写数据的代码部分出现了'str' does not support the buffer interface这样一个错误.
  一番搜索之后,发现py3里是严格区分了str和bytes的.怎么理解str和bytes呢?你可以认为str是一段文本,比如“abcd#%$^*&”什么的,而bytes呢,是二进制的一堆0,1的比特而已.看下面的图:

  可以看到str的类型是class 'str',而str.encode()以后类型是class 'bytes',这二者是不同的.而str.encode(‘gbk’)和str.encode('utf-8')得到的bytes的表示也是不同的.也就是说在采用不同的编码时,对同样的文本“哈哈”而言,其在内存中的那一堆01是不一样的.
  str和bytes之间可以通过encode(),decode()相互转化.

  下面是Python34\Lib\socket.py中的一段代码,可以看到在py3中,向一个socket file中写数据必须写的是bytes或是bytearray类型的



1    def write(self, b):
2         """Write the given bytes or bytearray object *b* to the socket
3         and return the number of bytes written.This can be less than
4         len(b) if not all data could be written.If the socket is
5         non-blocking and no bytes could be written None is returned.
6         """
7         self._checkClosed()
8         self._checkWritable()
9         try:
10             return self._sock.send(b)
11         except error as e:
12             # XXX what about EINTR?
13             if e.args in _blocking_errnos:
14               return None
15             raise
  所以在send(content)的时候如果content类型不是bytes或bytearray而是str的话就会出现'str' does not support the buffer interface的问题.将send(content)修正为send(content.encode())就好啦.
  
页: [1]
查看完整版本: Python 3中bytes和str的分别