BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python bytes() Function (With Examples)

Last Updated: July 6, 2021 by Chaitanya Singh | Filed Under: Python Tutorial

The bytearray() Function returns a bytes object, which is an immutable sequence of integers in the range 0 <=x < 256. If you want mutable sequence of integers, use bytearray() function.

Table of contents

  • Syntax of bytes() Function
  • bytes() Parameters
  • Return value from bytes() function
  • Example 1: String to bytes array using bytes() function
  • Example 2: Array of bytes from an integer
  • Example 3: bytes object from a list
  • Example 4: When no parameter is passed to the bytes() method

Syntax of bytes() Function

bytes(source, encoding, error)

bytes() Parameters

As mentioned in the syntax of bytes() function, this method can take upto three parameters. All these three parameters are optional, when no parameter is passed to bytes(), it returns the array of size 0.

source (Optional) – It initializes the array of bytes. If the source is an integer, an empty bytearray object of the specified size is created and if the source is a String, make sure that you specify the encoding of the source.

encoding (Optional) – You must also provide encoding if the source is a string.

errors (Optional) – Actions that needs to be taken when the encoding of string fails.

Return value from bytes() function

The bytes() method returns an array of bytes of the given size.

Example 1: String to bytes array using bytes() function

When we pass the string to the bytes() method, we must also provide the encoding. In the following example, we are using two different encoding for the same string, as you can see in the output, we are getting different bytes object for each encoding.

str = "beginnersbook"

# encoding 'utf-8'
arr = bytes(str, 'utf-8')

#encdoing 'utf-16'
arr2 = bytes(str, 'utf-16')

print(arr)
print(arr2)

Output: