Sequence Types - Bytearray ========================== .. toctree:: :maxdepth: 1 Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _section_heading-Byte_Array: Byte Array ---------- **MUTABILITY:** Mutable The mutable brother of the bytes class. No dedicated Python syntax to create bytearray literals. Must use constructor. * Using the :py:class:`bytearray` constructor to create an empty object. For example: >>> foo = bytearray() >>> foo bytearray(b'') * Using the :py:class:`bytearray` constructor to create a zero-filled (i.e. null-filled) bytes objects of specified length. For example: >>> foo = bytearray(4) >>> foo bytearray(b'\x00\x00\x00\x00') * Using the :py:class:`bytearray` constructor to populate a :py:class:`bytearray` object with an iterable of integers. For example: >>> foo = bytearray((1, 3, 5)) >>> foo bytearray(b'\x01\x03\x05') * Using the :py:class:`bytearray` constructor to encode a string into a :py:class:`bytearray`. This may require encoding each character into more than one byte depending on it's code point. For example: >>> foo = bytearray('Ѱ', encoding='utf8') bytearray(b'\xd1\xb0') .. note:: There is no method on the :py:class:`str` to encode a string into a :py:class:`bytearray` object like there is for encoding the :py:class:`str` into a :py:class:`bytes` object. .. _section_heading-Byte_Array_Specific_Methods: Byte Array Specific Methods ^^^^^^^^^^^^^^^^^^^^^^^^^^^ The :py:class:`bytearray` class supports all the same methods as the :py:class:`bytes` class. .. admonition:: Try it! :class: TryIt Try creating the following objects: * An empty bytearray object. * A bytearray object of 32 bytes, all 0. * A bytearray object from ASCII printable characters. * A bytearray object using character escape sequences. * A bytearray object from a tuple or list, such as [32, 48, 64]. * A bytearray object representing the character "ɸ" in UTF-8. * A bytearray object representing the character "ɸ" in UTF-16. * Get the string given by the following bytearray object, bytearray('\x48\x65\x6c\x6c\x6f', encoding='utf8').