Python内置bytes函数的详细介绍
英文文档:
class bytes([source[, encoding[, errors]]])
Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.
Accordingly, constructor arguments are interpreted as for bytearray().
说明:
1. 返回值为一个新的不可修改字节数组,每个数字元素都必须在0 - 255范围内,是bytearray函数的具有相同的行为,差别仅仅是返回的字节数组不可修改。
2. 当3个参数都不传的时候,返回长度为0的字节数组
>>> b = bytes() >>> b b'' >>> len(b) 0</p> <p style="text-align: left;"> 3. 当source参数为<a href="http://www.php.cn/wiki/57.html" target="_blank">字符串</a>时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组</p> <pre class="brush:php;toolbar:false">>>> bytes('中文') #需传入编码格式 Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> bytes('中文') TypeError: string argument without an encoding >>> bytes('中文','utf-8') b'\xe4\xb8\xad\xe6\x96\x87' >>> '中文'.encode('utf-8') b'\xe4\xb8\xad\xe6\x96\x87'
4. 当source参数为整数时,返回这个整数所指定长度的空字节数组
>>> bytes(2) b'\x00\x00' >>> bytes(-2) #整数需大于0,用于做数组长度 Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> bytes(-2) ValueError: negative count
5. 当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回
6. 当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里
>>> bytes([1,2,3]) b'\x01\x02\x03' >>> bytes([256,2,3]) Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> bytes([256,2,3]) ValueError: bytes must be in range(0, 256)</p> <p style="text-align: left;"> 7. 返回数组不可修改</p> <pre class="brush:php;toolbar:false">>>> b = bytes(10) >>> b b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' >>> b[0] >>> b[1] = 1 #不可修改 Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> b[1] = 1 TypeError: 'bytes' object does not support item assignment >>> b = bytearray(10) >>> b bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') >>> b[1] = 1 #可修改 >>> b bytearray(b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00')
以上是Python内置bytes函数的详细介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

在Python中,如何通过字符串动态创建对象并调用其方法?这是一个常见的编程需求,尤其在需要根据配置或运行...

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

本文讨论了诸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和请求等流行的Python库,并详细介绍了它们在科学计算,数据分析,可视化,机器学习,网络开发和H中的用途

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...
