{"id":25526,"date":"2021-11-19T09:12:35","date_gmt":"2021-11-19T03:42:35","guid":{"rendered":"https:\/\/python-programs.com\/?p=25526"},"modified":"2021-11-19T09:12:35","modified_gmt":"2021-11-19T03:42:35","slug":"python-bytearray-function-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-bytearray-function-with-examples\/","title":{"rendered":"Python bytearray() Function with Examples"},"content":{"rendered":"

bytearray() Function in Python:<\/strong><\/p>\n

The function bytearray() returns a bytearray object.<\/p>\n

It can either convert objects to bytearray objects or create an empty bytearray object of the specified size.<\/p>\n

The source parameter can be used to initialize the byte array in a variety of ways, including:<\/p>\n

String:<\/strong> str. encode() is used to convert the string to bytes () Encoding and, optionally, errors must also be provided.<\/p>\n

Integer:<\/strong> Creates an array of the specified size, with all elements set to null.<\/p>\n

Object:<\/strong> The object’s read-only buffer will be used to initialize the byte array.<\/p>\n

Iterable:<\/strong> Creates an array with the same size as the iterable count and initialized with the iterable elements. It must be iterable over integers between 0 <= x < 256<\/p>\n

No source(arguments):<\/strong> Makes a 0-dimensional array.<\/p>\n

Syntax:<\/strong><\/p>\n

bytearray(x, encoding, error)<\/pre>\n

Parameters<\/strong><\/p>\n

x:<\/strong> When creating the bytearray object, this is the source that will be used. If it is an integer, it will create an empty bytearray object of the specified size.<\/p>\n

If it’s a String, make sure to specify the source’s encoding.<\/p>\n

encoding:<\/strong> It is the string’s encoding<\/p>\n

error:<\/strong> Specifies what should happen if the encoding fails.<\/p>\n

Return Value:\u00a0<\/strong><\/p>\n

The bytearray() method returns a bytearray of the specified size and initialization values.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given Number = 5<\/pre>\n

Output:<\/strong><\/p>\n

The bytearray object of the given number 5 = bytearray(b'\\x00\\x00\\x00\\x00\\x00')<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given String = \"good morning btechgeeks\"\r\n# string with 'utf-8' encoding<\/pre>\n

Output:<\/strong><\/p>\n

The bytearray object of the given string =  bytearray(b'good morning btechgeeks')<\/pre>\n

bytearray() Function with Examples in Python<\/h2>\n