Python 내장 함수 (7) - bytearray

2503 단어
영문 문서:
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.

  • Without an argument, an array of size 0 is created.
    설명:
    1. 새 바이트 그룹으로 되돌아오는 값
    2. 3개의 매개 변수가 전송되지 않을 때 길이가 0인 바이트 그룹을 되돌려줍니다.
    >>> b = bytearray()
    >>> b
    bytearray(b'')
    >>> len(b)
    0
    

    3.source 매개 변수가 문자열일 때encoding 매개 변수도 제공해야 합니다. 함수는 문자열을str.encode 방법으로 바이트 그룹으로 변환합니다
    >>> bytearray(' ')
    Traceback (most recent call last): 
      File "", line 1, in  
        bytearray(' ')
    TypeError: string argument without an encoding
    >>> bytearray(' ','utf-8')
    bytearray(b'\xe4\xb8\xad\xe6\x96\x87')
    

    4.source 매개 변수가 정수일 때 이 정수가 지정한 길이의 빈 바이트 그룹을 되돌려줍니다
    >>> bytearray(2)
    bytearray(b'\x00\x00')
    >>> bytearray(-2) # 0, 
    Traceback (most recent call last): 
      File "", line 1, in  
        bytearray(-2)
    ValueError: negative count
    

    5.source 매개 변수가buffer 인터페이스의object 대상을 실현하기 위해, 읽기 전용 방식으로 바이트를 바이트 그룹으로 읽고 되돌려줍니다.
    6.source 매개 변수가 교체 가능한 대상이면 이 교체 대상의 요소는 모두 0<=x<256에 부합해야 수조에 초기화할 수 있습니다
    >>> bytearray([1,2,3])
    bytearray(b'\x01\x02\x03')
    >>> bytearray([256,2,3]) # 0-255 
    Traceback (most recent call last): 
      File "", line 1, in  
        bytearray([256,2,3])
    ValueError: byte must be in range(0, 256)
    

    좋은 웹페이지 즐겨찾기