Python每天必学之bytes字节
Python中的字节码用b'xxx'的形式表示。x可以用字符表示,也可以用ASCII编码形式\xnn表示,nn从00-ff(十六进制)共256种字符。
一、基本操作
下面列举一下字节的基本操作,可以看出来它和字符串还是非常相近的:
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
如果想要修改一个字节串中的某个字节,不能够直接修改,需要将其转化为bytearray后再进行修改:
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')
二、字节与字符的关系
上面也提到字节跟字符很相近,其实它们是可以相互转化的。字节通过某种编码形式就可以转化为相应的字符。字节通过encode()方法传入编码方式就可以转化为字符,而字符通过decode()方法就可以转化为字节:
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'
我们可以看到用不同的编码方式解析出来的字符和字节的方式是完全不同,如果编码和解码用了不同的编码方式,就会产生乱码,甚至转换失败。因为每种编码方式包含的字节种类数目不同,如上例中的\xc8就超出了utf-8的最大字符。
三、应用
举个最简单的例子,我要爬取一个网页的内容,现在来爬取用百度搜索Python时返回的页面,百度用的是utf-8编码格式,如果不对返回结果解码,那它就是一个超级长的字节串。而进行正确解码后就可以显示一个正常的html页面。
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程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
