The Wayback Machine - https://web.archive.org/web/20240921063208/https://www.geeksforgeeks.org/python-bytes-method/
Open In App

Python bytes() method

Last Updated : 16 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Example:

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)

Parameters:

  • 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.

Python3




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


Output:

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.

Python3




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


Output:

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

Null parameters with bytes()

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

Python3




print(bytes())


Output:

b''

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.

Python3




# 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)))


Output: 

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 ‘?’.

Example: 

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.

Python3




# 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')))


Output: 

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

Exception:

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


Previous Article
Next Article

Similar Reads

Find length of one array element in bytes and total bytes consumed by the elements in Numpy
In NumPy we can find the length of one array element in a byte with the help of itemsize . It will return the length of the array in integer. And in the numpy for calculating total bytes consumed by the elements with the help of nbytes. Syntax: array.itemsize Return :It will return length(int) of the array in bytes. Syntax: array.nbytes Return :It
1 min read
NumPy ndarray.byteswap() Method | Swap bytes of the Array Elements
The ndarray.byteswap() method swaps the bytes of the array elements. It toggles between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place. Note: byteswap() method does not work on arrays of strings. Example C/C++ Code # Python program explaining # byteswap() function import numpy as geek # a
2 min read
Python - Write Bytes to File
Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file There are four basic modes in which a file can be opened― read, write, append, and exclusive c
2 min read
How to Convert Bytes to Int in Python?
A bytes object can be converted to an integer value easily using Python. Python provides us various in-built methods like from_bytes() as well as classes to carry out this interconversion. int.from_bytes() method A byte value can be interchanged to an int value by using the int.from_bytes() method. This method requires at least Python 3.2 and has t
2 min read
Retaining the padded bytes of Structural Padding in Python
Structural Padding means aligning the data into blocks of fixed size in order to ease the operations of particular Computer Architectures, Cryptographic algorithms accordingly. We pad(add enough bytes) the operational data (which is not necessarily structured) in order to serve the machine. Padded bytes may interrupt the original data, to identify
2 min read
How to Convert Bytes to String in Python ?
In this article, we are going to cover various methods that can convert bytes to strings using Python. Convert bytes to a string Different ways to convert Bytes to string in Python: Using decode() methodUsing str() functionUsing codecs.decode() methodUsing map() without using the b prefixUsing pandas to convert bytes to strings Data types are the c
3 min read
Convert Bytes To Bits in Python
Among the must-have computer science and programming skills, having bit-level knowledge is one of those important things that you should know what it means to understand the data change in this big world. However, a potential need often arises for the conversion of bytes and bits in digital information into alternative units. In this article, we wi
2 min read
Convert Bytearray To Bytes In Python
In Python, dealing with binary data is a common task, and understanding how to convert between different binary representations is crucial. One such conversion is from a bytearray to bytes. In this article, we will explore five simple methods to achieve this conversion, along with code examples for each. Convert Bytearray To Bytes In PythonBelow, a
3 min read
Convert Unicode to Bytes in Python
Unicode, often known as the Universal Character Set, is a standard for text encoding. The primary objective of Unicode is to create a universal character set that can represent text in any language or writing system. Text characters from various writing systems are given distinctive representations by it. Convert Unicode to Byte in PythonBelow, are
2 min read
Convert Hex String to Bytes in Python
Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. In Python, converting a hex string to bytes is a frequent task, and there are various methods to achieve this. In this article, we will explore some simple and commonly used methods for converting a hex string to b
3 min read
Convert a Bytes Array into Json Format in Python
In Python, dealing with bytes data is common, and converting a bytes array to JSON format is a frequent task. In this article, we will see how to convert a bytes array into JSON format in Python. Python Convert a Bytes Array into JSON FormatBelow are some of the ways by which we can convert a bytes array into JSON format in Python: Using decode and
3 min read
Convert from '_Io.Bytesio' to a Bytes-Like Object in Python
In Python, converting from _io.BytesIO to a bytes-like object involves handling binary data stored in a BytesIO object. This transformation is commonly needed when working with I/O operations, allowing seamless access to the raw byte representation contained within the BytesIO buffer. Various methods can be used to Convert From '_Io.Bytesio' To A B
2 min read
How to Convert Int to Bytes in Python?
An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. Method 1: int.tobytes() An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an i
4 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Python | os.abort() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.abort() method in Python is used to generate a SIGABRT signal to the current process. On Unix, this method produces a core dump
2 min read
Python | os.renames() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.renames() method is a recursive directory or file renaming function. It works like os.rename() method except creation of any int
2 min read
Python | os.lseek() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.lseek() method sets the current position of file descriptor fd to the given position pos which is modified by how. Syntax: os.ls
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | PyTorch sin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sin() provides support for the sine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1]. The input type is tensor and if the input conta
2 min read
Python | Sympy Line.is_parallel() method
In Sympy, the function is_parallel() is used to check whether the two linear entities are parallel or not. Syntax: Line.is_parallel(l2) Parameters: l1: LinearEntity l2: LinearEntity Returns: True: if l1 and l2 are parallel, False: otherwise. Example #1: # import sympy and Point, Line from sympy import Point, Line p1, p2 = Point(0, 0), Point(1, 1) p
1 min read
Python PIL | GaussianBlur() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method. PIL.ImageFilter.GaussianBlur() method create Gaussian blur filter. Syntax: PIL.ImageFilter.GaussianBlur(radius=5) Par
1 min read