Python bytes() method (original) (raw)

Last Updated : 02 Jan, 2025

bytes() method in Python is used to create a sequence of bytes. In this article, we will check How bytes() methods works in Python.

Python `

a = "geeks"

UTF-8 encoding is used

b = bytes(a, 'utf-8') print(b)

`

Table of Content

Syntax of bytes()

bytes(]])

**Parameters:

source (optional)

encoding (optional)

This parameter is used when the source is a string. It specifies the encoding format to convert the string into bytes. The default encoding is ‘utf-8’ but you can use other encodings like ‘ascii’, ‘utf-16’, etc.

errors (optional)

Defines how to handle errors during the encoding process.

**Return Type:

Using Custom Encoding

If the string contains characters from other languages, we can specify a different encoding:

Python `

a = "गीक्स" b = bytes(a, 'utf-16')

Converts the string to bytes using UTF-16 encoding

print(b)

`

Output

b'\xff\xfe\x17\t@\t\x15\tM\t8\t'

**Convert String to Bytes

Python String to bytes using the bytes() function, for this we take a variable with string and pass it into the bytes() function with UTF-8 parameters. When we pass a string to the bytes() method, we also need to tell Python which “language” (encoding) to use to convert the string.

Python `

s = "Welcome to Geeksforgeeks"

b = bytes(s, 'utf-8')

print(b)

`

Output

b'Welcome to Geeksforgeeks'

Converting a List of Integers to Bytes

Each number in the list must be between 0 and 255 because each byte can only hold numbers in that range. When we pass a list of numbers to the bytes() method, Python will create a bytes object where each number in the list corresponds to one byte.

Python `

a = [215, 66, 67]

Converts the list of integers into bytes

b = bytes(a) print(b)

`

**Creating a Bytes Object with a Specific Size

By passing a single integer to bytes(), Python will create a bytes object of that length, filled with zero values (because a byte is initially 0).

Python `

a = 5

Creates a bytes object of length 5, with all zero values

b = bytes(a)
print(b)

`

Output

b'\x00\x00\x00\x00\x00'