Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

What is bytes() in Python?

Mahnoor Zaheer

The bytes() function converts an object (such as a list, string, integers, etc.) into an immutable bytes object within the range of 0 to 256. If no object is provided to the bytes() method, it can generate an empty bytes object of a specified size.

Syntax

This method can be declared in two ways, depending on the requirement:

The two types of syntaxes of bytes() method in Python

Parameters and return value

The return value of the bytes() function varies in two ways depending upon the parameters:

  1. If an integer indicating the size of the bytes is passed into the function, it returns an empty bytes object of the specified size.

  2. Instead of a size, a string, tuple, or a list is passed into the bytes() method, it is converted into a corresponding bytes object. In this case, the encoding for the string, tuple, or list can be specified, and hence encoding is an optional parameter.

  3. A third optional argument is passed in the function that tells what to do if the method fails to cater to the errors.

Code

An empty bytes object of a specific size is created in the example below, i.e., 6.

# specify size
size = 6

#generate empty bytes object of size 6: 
byteArray = bytes(size)

# output: b'\x00\x00\x00\x00\x00\x00'
print(byteArray)
Code for generating a bytes object of size 6

Here, no specific size of the required bytes is given because an object, i.e., string, is passed into the function. Also, the encoding method “utf-8” is provided in the given instance:

givenString = ["Welcome", "to", "educative"]

# given_string is encoded into bytes object according to utf-8
byteArray = bytes(givenString,'útf-8')

# output: b'Welcome to educatve'
print(byteArray)

Similarly, an object, in this case, a tuple is passed into the bytes() function to generate bytes object corresponding to it without mentioning any encoding type.

tup = (1, 2, 3, 4, 5)

# tuple is converted into bytes object without specifying any encoding type
byteArray = byte(tup)

# outputs: b'\x01\x02\x03\x04\x05'
print(byteArray)
Code for converting a tuple into bytes object

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring