Open In App
Related Articles

Python bytes() method

Improve Article
Save Article
Like Article

Python byte() function converts an object to an immutable byte-represented object of a given size and data.


Input: 2
Output: b'\x00\x00'

Input: Python
Output: b'Python'

Python bytes() Method Syntax

The bytes() method in Python has the following syntax.

Syntax : bytes(src, enc, err)


  • src : The source object which has to be converted
  • enc : The encoding required in case object is a string
  • err : Way to handle error in case the string conversion fails.

Returns:  Byte immutable object consisting of unicode 0-256 characters according to src type. 

  • integer : Returns array of size initialized to null
  • iterable : Returns array of iterable size with elements equal to iterable elements( 0-256 )
  • string : Returns the encoded string acc. to enc and if encoding fails, performs action according to err specified.
  • no arguments : Returns array of size 0.

bytes() Method in Python Examples

Let us see a few examples of the Python bytes() method.

Convert String to Bytes

In this example, we will convert 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. UTF-8 is capable of encoding all 1,112,064 valid character code points in Unicode using one to four one-byte code units.


# python code demonstrating
# int to bytes
str = "Welcome to Geeksforgeeks"
arr = bytes(str, 'utf-8')


b'Welcome to Geeksforgeeks'

Convert Integer to Bytes

In this example, we are going to see how to get an array of bytes from an integer using the bytes() function in Python. For this, we will pass the integer into the bytes() function.


# python code to demonstrate
# int to bytes
number = 12
result = bytes(number)



Null parameters with bytes()

When we pass nothing to the bytes() function, it creates an array of size 0.





Demonstrating byte() on Integers, None and Iterables

In this example, when nothing is passed to the bytes() method, it returns an empty object. But when an integer or a Python List is provided as a parameter to the bytes() method, it converts and returns the byte object representation of the integer or the list.


# Python 3 code to demonstrate the
# working of bytes() on int, iterables, none
# initializing integer and iterables
a = 4
lis1 = [1, 2, 3, 4, 5]
# No argument case
print ("Byte conversion with no arguments : " + str(bytes()))
# conversion to bytes
print ("The integer conversion results in : "  + str(bytes(a)))
print ("The iterable conversion results in : "  + str(bytes(lis1)))


Byte conversion with no arguments : b''
The integer conversion results in : b'\x00\x00\x00\x00'
The iterable conversion results in : b'\x01\x02\x03\x04\x05'

The Behavior of Bytes with Strings 

Bytes accept a string as an argument and require an encoding scheme with it to perform it. The most important aspect of this is handling errors in case of encoding failure, some of the error handling schemes defined are : 

String Error Handlers:

  • strict : Raises the default UnicodeDecodeError in case of encode failure.
  • ignore : Ignores the unencodable character and encodes the remaining string.
  • replace : Replaces the unencodable character with a ‘?’.


Let’s consider a string that contains ASCII and non-ASCII values. When the bytes() method encounters a non-ASCII character and the errors parameter of the bytes() method is set to ‘ignore’, it simply ignores the non-ascii character and prints the rest of the string. When the errors parameter is set to ‘replace’, the bytes()  method replaces the character with the question mark ‘?’ and when the errors parameter is set to ‘strict’, it will raise a ‘UnicodeEncodeError’ exception.


# Python 3 code to demonstrate the
# working of bytes() on string
# initializing string
str1 = 'GeeksfĂ–rGeeks'
# Giving ascii encoding and ignore error
print("Byte conversion with ignore error : " +
      str(bytes(str1, 'ascii', errors='ignore')))
# Giving ascii encoding and replace error
print("Byte conversion with replace error : " +
      str(bytes(str1, 'ascii', errors='replace')))
# Giving ascii encoding and strict error
# throws exception
print("Byte conversion with strict error : " +
      str(bytes(str1, 'ascii', errors='strict')))


Byte conversion with ignore error : b'GeeksfrGeeks'
Byte conversion with replace error : b'Geeksf?rGeeks'


UnicodeEncodeError: 'ascii' codec can't encode character '\xd6' in position 6: ordinal not in range(128)

Last Updated : 16 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials