Function Details: bytes

Description


Returns a new 'bytes' object, which is an immutable sequence of integers in the range 0 <= x < 256.


Extended Description


The bytes() function creates an immutable sequence of bytes. It can be initialized in various ways: from an iterable of integers, from a string with a specified encoding, from another bytes or bytearray object, or by creating a sequence of null bytes of a specified length.


Exceptions


  • ValueError: If any integer in the iterable is outside the range 0 <= x < 256
  • TypeError: If the source argument has an inappropriate type

Read More about bytes from Python Documentation

Function Signature


bytes(source: Union[int, Iterable[int], str, bytes] = None, encoding: str = None, errors: str = None) -> bytes

Module: builtins

Parameters


source: Can be an integer (to create that many null bytes), an iterable of integers 0 <= x < 256, a string (requires encoding to be specified), or an object that implements the buffer protocol. encoding: The encoding to use if source is a string. Common values include 'utf-8', 'ascii', etc. errors: Specifies how to handle encoding errors. Common values are 'strict', 'ignore', 'replace', etc.


Parameter List


  • source: Union[int, Iterable[int], str, bytes]
  • encoding: str
  • errors: str

Return


Returns a new bytes object, which is an immutable sequence of integers in the range 0 <= x < 256.


Return Type


bytes

Output

Explanation

This example shows how to create bytes objects from an iterable of integers, a string with encoding, and an integer (creating null bytes).