Python内置函数—bytearray

英文文档:

class bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
  • If it is an integer, the array will have that size and will be initialized with null bytes.
  • If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
  • If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array

    def __init__(self, source=None, encoding=None, errors=‘strict‘): # known special case of bytearray.__init__
        """
        bytearray(iterable_of_ints) -> bytearray
        bytearray(string, encoding[, errors]) -> bytearray
        bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
        bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
        bytearray() -> empty bytes array

        Construct a mutable bytearray object from:
          - an iterable yielding integers in range(256)
          - a text string encoded using the specified encoding
          - a bytes or a buffer object
          - any object implementing the buffer API.
          - an integer
        # (copied from class doc)
        """
        pass

bytearray

返回一个新的字节数组。
bytearray类是range 0 < = x < 256的一个可变序列。
它有大多数可变序列的常用方法,在可变序列类型中描述,以及大多数字节类型的方法,参见字节和Bytearray操作。

可选的源参数可以用几种不同的方式来初始化数组:

  • 如果它是一个字符串,那么您还必须给出编码(以及可选的错误)参数;bytearray()然后使用str.encode()将字符串转换为字节。
  • 如果它是一个整数,那么数组将具有这个大小,并将用null字节初始化。
  • 如果它是符合缓冲区接口的对象,则将使用对象的只读缓冲区来初始化字节数组。
  • 如果它是可迭代的,那么它必须是range 0 < = x < 256的整数的迭代,它被用作数组的初始内容

如果没有参数,则创建一个大小为0的数组。

说明:
1. 返回值为一个新的字节数组
2. 当3个参数都不传的时候,返回长度为0的字节数组

#!/usr/bin/python3

b = bytearray()
print(b)print(len(b))

结果:

bytearray(b‘‘)
0

3. 当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组

b = bytearray(‘中文‘)

结果:

Traceback (most recent call last):
  File "D:/py/day001/day1/test.py", line 3, in <module>
    b = bytearray(‘中文‘)
TypeError: string argument without an encoding

encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组

b = bytearray(‘中文‘, ‘utf-8‘)
print(b)
print(len(b))

结果:

bytearray(b‘\xe4\xb8\xad\xe6\x96\x87‘)
6

4. 当source参数为整数时,返回这个整数所指定长度的空字节数组

#!/usr/bin/python3

b = bytearray(5)
print(b)
print(len(b))

执行结果:

bytearray(b‘\x00\x00\x00\x00\x00‘)
5

5. 当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回

#!/usr/bin/python3

b = bytearray([1,2,3,4,5])
print(b)
print(len(b))

执行结果:

bytearray(b‘\x01\x02\x03\x04\x05‘)
5

6. 当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里

#!/usr/bin/python3

b = bytearray([1,2,3,4,5,256])
print(b)
print(len(b))

执行结果:

Traceback (most recent call last):
  File "D:/py/day001/day1/test.py", line 3, in <module>
    b = bytearray([1,2,3,4,5,256])
ValueError: byte must be in range(0, 256)

  

时间: 2024-07-29 04:56:42

Python内置函数—bytearray的相关文章

Python内置函数——bytearray()-暂疑

英文文档: class bytearray([source[, encoding[, errors]]]) Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence

Python补充--Python内置函数清单

Python内置函数 Python内置(built-in)函数随着python解释器的运行而创建.在Python的程序中,你可以随时调用这些函数,不需要定义.最常见的内置函数是: print("Hello World!") 在Python教程中,我们已经提到下面一些内置函数:基本数据类型 type()反过头来看看 dir()   help()    len()词典 len()文本文件的输入输出 open()循环设计 range()   enumerate()    zip()循环对象

python学习系列--python内置函数(一)

先列出所有的python内置函数,可以看到还是挺多的. abs()        求给定数的绝对值. all()          传入一个列表,只有当列表中所有元素都是真时,该函数返回真. any()        传入一个列表,只要列表中有一个元素为真,该函数即返回真. ascii()       执行对象中的__repr__方法.该函数在python2.7中已弃用. bin()         将给定的值转换成二进制. bool()       判断真假. bytearray()     

Python内置函数(61)——str

英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is give

Python之路Python内置函数、zip()、max()、min()

Python之路Python内置函数.zip().max().min() 一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算,如果全部都是true,就返回true, 但是如果是空字符串.空列表也返回true 例子 print(all([1,2,'1',''])) 输出结果 False 例子2 print(all('')) 输出结果 True any() 把序列中每一个元素做布尔运算,如果有一个为true就返回true, 但

Python内置函数_数学运算类

本文和大家分享的主要是python内置函数数据运算类相关内容,一起来看看吧,希望对大家学习python 有所帮助. abs abs(x) 求绝对值 · X可以是整型,也可以是复数 · 若X是复数,则返回复数的模 >>> abs(-1)1>>> abs(-3+4j)5.0>>> bin bin(x) 将整数x转换为二进制字符串 >>> bin(2)'0b10'>>> bin(3)'0b11' bool bool([x]

Python内置函数进制转换的用法

使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns a

python基础9 -----python内置函数

python内置函数1 一.python内所有的内置函数: 二.python内常用的内置函数: 三.python内内置函数详解: 1.数学运算函数: 2.集合类函数: 3.逻辑类函数: 4.映射类函数: 5.IO操作:

Python 内置函数sorted()有哪些高级用法?

本文和大家分享的主要是python内置函数sorted()的相关内容,一起来看看吧,希望对大家学习python http://www.maiziedu.com/land/python/有所帮助. 1.对于 Python 内置函数 sorted() ,先拿来跟list(列表)中的成员函数 list.sort() 进行下对比.在本质上,list的排序和内建函数sorted的排序是差不多的,连参数都基本上是一样的. 2.主要的区别在于, list.sort() 是对已经存在的列表进行操作,进而可以改变