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
- bytes() Method Syntax
- Using Custom Encoding
- Convert String to Bytes
- Converting a List of Integers to Bytes
- Creating a Bytes Object with a Specific Size
Syntax of bytes()
bytes(]])
**Parameters:
source (optional)
- A **string will be encoded into bytes using the specified encoding (default is ‘utf-8’).
- An **iterablewill have each element converted into bytes but it must have integers between 0 and 255.
- An **integer creates a bytes object of that size with all elements initialized to 0.
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.
- ‘**strict‘: Raises a UnicodeEncodeError if there is an error.
- ‘**ignore‘: Ignores characters that can’t be encoded.
- ‘**replace‘: Replaces characters that can’t be encoded with a placeholder (usually a question mark).
**Return Type:
- return type of the bytes() method is a bytes object. A bytes object is an immutable sequence of integers in the range from 0 to 255.
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'