The Wayback Machine - https://web.archive.org/web/20240617161606/https://www.geeksforgeeks.org/byte-objects-vs-string-python/
Open In App

Byte Objects vs String in Python

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Python 2, both str and bytes are the same typeByte objects whereas in Python 3 Byte objects, defined in Python 3 are “sequence of bytes” and similar to “unicode” objects from Python 2. In this article, we will see the difference between byte objects and strings in Python and also will look at how we can convert byte string to normal string and vice versa.

Byte Objects vs String in Python

S.NO

Byte Object

Python String

1.

Byte objects are a sequence of Bytes.

Strings are a sequence of characters.

2.

Byte objects are in machine-readable form internally.

Strings are only in human-readable form.

3.

Bytes are used to handle binary data.

Strings are used to handle textual data.

4.

They can be directly stored on the disk.

They need encoding before they are stored on disk.

string vs byte in python

Convert String to Byte Objects (Encoding)

PNG, JPEG, MP3, WAV, ASCII, UTF-8 etc are different forms of encodings. An encoding is a format to represent audio, images, text, etc in bytes. Converting Strings to byte objects is termed as encoding. This is necessary so that the text can be stored on disk using mapping using ASCII or UTF-8 encoding techniques.
This task is achieved using encode(). It take encoding technique as argument. Default technique is “UTF-8” technique.

Python3




# Python code to demonstrate String encoding
# initialising a String
a = 'GeeksforGeeks'
 
# initialising a byte object
c = b'GeeksforGeeks'
 
# using encode() to encode the String
d = a.encode('ASCII')
 
# checking if a is converted to bytes or not
if (d==c):
    print ("Encoding successful")
else : print ("Encoding Unsuccessful")


Output

Encoding successful

Convert Byte Objects to String (Decoding)

Similarly, Decoding is process to convert a Byte object to String. It is implemented using decode() . A byte string can be decoded back into a character string, if you know which encoding was used to encode it. Encoding and Decoding are inverse processes. 

Python3




# Python code to demonstrate Byte Decoding
# initialising a String
a = 'GeeksforGeeks'
 
# initialising a byte object
c = b'GeeksforGeeks'
 
# using decode() to decode the Byte object
d = c.decode('ASCII')
 
# checking if c is converted to String or not
if (d==a):
    print ("Decoding successful")
else : print ("Decoding Unsuccessful")


Output

Decoding successful

Concatenating a String and a Byte String

In this example, we have defined a string “Geeks” and a byte string “forGeeks”. After that we used decode() method to convert byte string to normal string and then concatenate both of them.

Python3




# Define a string
string = "Geeks"
 
# Define a byte string
byte_str = b"forGeeks"
 
# Concatenate the string and byte string
ans = string + byte_str.decode()
print(ans)


Output

GeeksforGeeks



Similar Reads

Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python program to convert a byte string to a list of integers
Given a byte string. The task is to write a Python program to convert this byte of string to a list of integers. Method 1: By using list() function The list() function is used to create a list from the specified iterable taken as its parameter. Syntax: list([iterable]) Parameters: This function accepts a single parameter that is illustrated below:
5 min read
Python - Interconvert Tuple to Byte Integer
Sometimes, while working with Python data, we can have a problem in which we need to perform conversion of tuple values, into combined byte and then to integer and vice-versa. This kind of problem can have application in data domains. Let's discuss certain ways in which this task can be performed. Input : test_tuple = (1, 2, 3, 4, 5) Output : 43287
2 min read
How to generate byte code file in python ?
Whenever the Python script compiles, it automatically generates a compiled code called as byte code. The byte-code is not actually interpreted to machine code, unless there is some exotic implementation such as PyPy. The byte-code is loaded into the Python run-time and interpreted by a virtual machine, which is a piece of code that reads each instr
2 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-class that is used to count hashable objects. It im
5 min read
Python Tkinter | Moving objects using Canvas.move() method
The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level. Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x
2 min read
Python | Unit Test Objects Patching | Set-1
The problem is writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.). To do so, the unittest.mock.patch() function can be used to help with this problem. It’s a little unusual
2 min read
Article Tags :
Practice Tags :