Open In App

Python | Convert String to bytes

Last Updated : 21 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Inter conversions are as usual quite popular, but conversion between a string to bytes is more common these days due to the fact that for handling files or Machine Learning ( Pickle File ), we extensively require the strings to be converted to bytes. Let’s discuss certain ways in which this can be performed.

 Method #1 : Using bytes(str, enc) String can be converted to bytes using the generic bytes function. This function internally points to CPython Library which implicitly calls the encode function for converting the string to specified encoding. 

Python3




# Python code to demonstrate
# convert string to byte
# Using bytes(str, enc)
 
# initializing string
test_string = "GFG is best"
 
# printing original string
print("The original string : " + str(test_string))
 
# Using bytes(str, enc)
# convert string to byte
res = bytes(test_string, 'utf-8')
 
# print result
print("The byte converted string is  : " + str(res) + ", type : " + str(type(res)))


Output : 

The original string : GFG is best
The byte converted string is  : b'GFG is best', type : <class 'bytes'>

  Method #2 : Using encode(enc) The most recommended method to perform this particular task, using the encode function to get the conversion done, as it reduces one extra linking to a particular library, this function directly calls it. 

Python3




# Python code to demonstrate
# convert string to byte
# Using encode(enc)
 
# initializing string
test_string = "GFG is best"
 
# printing original string
print("The original string : " + str(test_string))
 
# Using encode(enc)
# convert string to byte
res = test_string.encode('utf-8')
 
# print result
print("The byte converted string is  : " + str(res) + ", type : " + str(type(res)))


Output : 

The original string : GFG is best
The byte converted string is  : b'GFG is best', type : <class 'bytes'>

Method #2 : Using memoryview()

In this example, we’re calling the encode() method on the my_string variable to convert it to bytes using the UTF-8 encoding. Then we’re passing the resulting bytes object to the memoryview() function, which returns a memory view object that provides a view of the underlying bytes.

Finally, we’re calling the tobytes() method on the memory view object to create a new bytes object containing the same data. This bytes object is stored in the my_bytes variable and printed out to the console.

NOTE: memoryview() function is useful for situations where you need to access the underlying bytes of an object without copying them. However, it may not be the most efficient approach for simple string-to-bytes conversion, as it involves additional overhead.

Python3




my_string = "Hello, world!"  #Define a string called my_string with the value "Hello, world!".
my_bytes = memoryview(my_string.encode('utf-8')).tobytes()
 
#Encode the string as bytes using the UTF-8 encoding by calling the encode() method on my_string and passing 'utf-8' as the argument. This will return a bytes object containing the encoded bytes.
 
#Convert the memoryview object of the bytes object to bytes using the tobytes() method. This creates a new bytes object that is a copy of the original bytes object.
 
#Print the resulting bytes object using the print() function.#
 
print(my_bytes)


Output

b'Hello, world!'

time complexity: O(n), 

space complexity: O(n)

Method #3 :  Using binascii.unhexlify() method:

Algorithm :

1.Import the binascii module
2.Initialize a string containing the hexadecimal representation of bytes
3.Use the unhexlify() method of the binascii module to convert the hexadecimal string to bytes
4.Print the converted bytes and their type.

Python3




import binascii
 
# initializing string
test_string = "4766472069732062657374"
 
# printing original string
print("The original string : " + str(test_string))
 
# Using binascii.unhexlify()
# convert string to byte
res = binascii.unhexlify(test_string)
 
# print result
print("The byte converted string is : " + str(res) + ", type : " + str(type(res)))
#This code is contributed by  Jyothi pinjala


Output

The original string : 4766472069732062657374
The byte converted string is : b'GfG is best', type : <class 'bytes'>

Time Complexity:

The binascii.unhexlify() method has a time complexity of O(n), where n is the length of the input string.
All other operations in this code have a time complexity of O(1).
Therefore, the overall time complexity of this code is O(n).

Space Complexity:

The space complexity of this code is O(1), as it only uses a constant amount of extra space, regardless of the input size.

Method 5 :  using the struct.pack() method.

Step-by-Step approach 

Import the struct module in your code.
Initialize a string named ‘test_string’ with the value “GFG is best”.
Print the original string using the print statement.
Use the bytes() method to convert the string to bytes. Pass the ‘test_string’ and ‘utf-8’ encoding as parameters to the method.
Use the struct.pack() method to convert the bytes to binary data. Pass the format string ’10s’ and the bytes as parameters to the method. The ’10s’ format string indicates that the input data should be treated as a string of length 10.
Store the result in a variable ‘res’.
Print the converted byte string along with its type using the print statement.
 

Python3




import struct
 
# initializing string
test_string = "GFG is best"
 
# printing original string
print("The original string : " + str(test_string))
 
# Using struct.pack()
# convert string to byte
res = struct.pack('10s', bytes(test_string, 'utf-8'))
 
# print result
print("The byte converted string is  : " + str(res) + ", type : " + str(type(res)))


Output

The original string : GFG is best
The byte converted string is  : b'GFG is bes', type : <class 'bytes'>

Time complexity: The time complexity of the bytes() and struct.pack() methods is O(n) where n is the length of the input string.

Auxiliary Space: The space complexity of the bytes() and struct.pack() methods is O(n) where n is the length of the input string.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads