Javatpoint Logo
Javatpoint Logo

Python bytearray() Method

Python bytearray() method returns a new array of bytes. This method takes an optional argument and returns result based on the argument type.

This method uses following type of source parameter to initialize the array in a few different ways:

  1. If parameter is a string, we must also give the encoding parameters. The method then converts the string to bytes using str.encode().
  2. If parameter is an integer, the array will have that size and will be initialized with null bytes.
  3. 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.
  4. If no argument is provided, an array of size 0 is created.

Signature

Parameters

Source: A source value to convert into an array of bytes.

Encoding: if the source is string, must pass it's encoding.

Error: set error for the source.

Return

It returns an array of bytes.

Let's see some examples of bytearray() method to understand it's functionality.

Python bytearray() Method Example 1

This method returns byte array of a string with utf-8 encoding. See the example below.

Output:

bytearray(b'Hello Javatpoint')

Python bytearray() Method Example 2

Output:

bytearray(b'\x00\x00\x00\x00')
bytearray(b'\x01\x02\x19')

Python bytearray() Method Example 3

It returns an empty bytearray if no parameter is passed at calling time.

Output:

bytearray(b'')

Next TopicPython Functions




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA