好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python学习中必学的bytes字节

Python每天必学之bytes字节,针对Python中的bytes字节进行学习理解,感兴趣的小伙伴们可以参考一下

In[40]: b = b"abcd\x64"
In[41]: b
Out[41]: b'abcdd'
In[42]: type(b)
Out[42]: bytes
In[43]: len(b)
Out[43]: 5
In[44]: b[4]
Out[44]: 100 # 100用十六进制表示就是\x64 
In[46]: barr = bytearray(b)
In[47]: type(barr)
Out[47]: bytearray
In[48]: barr[0] = 110
In[49]: barr
Out[49]: bytearray(b'nbcdd') 
In[50]: s = "人生苦短,我用Python"
In[51]: b = s.encode('utf-8')
In[52]: b
Out[52]: b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python'
In[53]: c = s.encode('gb18030')
In[54]: c
Out[54]: b'\xc8\xcb\xc9\xfa\xbf\xe0\xb6\xcc\xa3\xac\xce\xd2\xd3\xc3Python'
In[55]: b.decode('utf-8')
Out[55]: '人生苦短,我用Python'
In[56]: c.decode('gb18030')
Out[56]: '人生苦短,我用Python'
In[57]: c.decode('utf-8')
Traceback (most recent call last):
 exec(code_obj, self.user_global_ns, self.user_ns)
 File "<ipython-input-57-8b50aa70bce9>", line 1, in <module>
 c.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte
In[58]: b.decode('gb18030')
Out[58]: '浜虹敓鑻︾煭锛屾垜鐢≒ython' 
import urllib.request

url = "http://www.baidu.com/s?ie=utf-8&wd=python"
page = urllib.request.urlopen(url)
mybytes = page.read()
encoding = "utf-8"
print(mybytes.decode(encoding))
page.close() 

以上就是本文的全部内容,希望对大家学习python程序设计有所帮助。

以上就是Python学习中必学的bytes字节的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于Python学习中必学的bytes字节的详细内容...

  阅读:49次