You are currently viewing Python Convert String to Bytes

How to convert strings to bytes in Python? Converting a string to bytes involves encoding the string using a specific character encoding. Both the string encode() method and the bytes() constructor can be used for this purpose. You can convert a string to bytes in Python by using the encode() method. This method takes an encoding as an argument and returns the corresponding bytes representation of the given string in that encoding. The bytes() constructor can also be used to convert a string to bytes. It takes two arguments, the source string and the encoding.

Advertisements

You can convert string to bytes in Python using many ways, for example, by using bytes(), encode(), binascii.unhexlify(), memoryview(), and struct.pack() functions. In this article, I will explain some methods of Python and using these methods how you can convert strings to bytes with multiple examples.

Related: In Python, you can also convert bytes to string very easily.

1. Quick Examples of Converting String to Bytes

Below are the most common methods for converting a string to a bytes. In the following sections, we will discuss each of these methods in detail with examples.


# Quick examples of converting string to bytes

import binascii
import struct

# Initializing string
string = "Welcome to Sparkbyexamples"

# Example 1: Using encode()
# to convert string to byte
result = string.encode('utf-8')


# Example 2: Using bytes(str, enc)
# to convert string to byte
result = bytes(string, 'utf-8')

# Example 3: Using binascii.unhexlify()
# to convert hexadecimal-encoded string to bytes
hex_string = "57656c636f6d6520746f20537061726b62796578616d706c6573"
result = binascii.unhexlify(hex_string)

# Example 4: Using memoryview() function
# to convert string to bytes
byte_view = memoryview(string.encode('utf-8'))
result = bytes(byte_view)

# Example 5: Convert string to bytes using memoryview
result = memoryview(string.encode('utf-8')).tobytes()

# Example 6: Using struct.pack() function
# to convert string to bytes
result = struct.pack('16s', bytes(string, 'utf-8'))

2. Convert String to Byte Using encode()

To convert a string to bytes in Python, use the encode() method. In this program, Apply this method over the string itself with the desired encoding (‘utf-8’ in this case). It returns a byte representation of the string encoded using the specified encoding. The result will also be an bytes object.


# Initializing string
string = "Welcome to Sparkbyexamples"
print("Original string:", string)

# Using encode()
# to convert string to bytes
result = string.encode('utf-8')
print("After converting the string to bytes:", result)
print("Type of the converted bytes:", type(result))

Yields below output.

python convert string bytes

In the above output, notice that the converted bytes are prefixed with a b to indicate that they are of the bytes type. The bytes type represents a sequence of bytes and is immutable, similar to a string.

3. Convert String to Bytes Using bytes()

You can use the bytes() constructor to convert a string to bytes, specifying the encoding as an argument. For example, first, initialize a string variable named string with the value "Welcome to Sparkbyexamples". Then use the bytes() constructor to convert the string to bytes using the UTF-8 encoding. The result is stored in the variable named result. The original string and the converted bytes are printed using the print() function. The type of the result variable is printed using the type() function.

The UTF-8 encoding is a widely used character encoding that represents characters using variable-length sequences of bytes. It can represent characters from various languages and also includes ASCII characters.


# Initializing string
string = "Welcome to Sparkbyexamples"
print("Original string:", string)

# Using bytes(str, enc)
# to convert string to byte
result = bytes(string, 'utf-8')
print("After converting the string to bytes:", result)
print("Type of the converted bytes:", type(result))

Yields the same output as above.

4. Using binascii.unhexlify() Method

Alternatively, you can use the binascii.unhexlify() method to convert hexadecimal-encoded data into binary data. For example, this method is used to decode the hexadecimal-encoded string back into bytes. The resulting bytes will be the binary representation of the original hexadecimal-encoded string.

Remember that the binascii.unhexlify() method is used specifically for converting hexadecimal-encoded data, so it’s not the same as encoding a regular string to bytes using an encoding like UTF-8.


import binascii

# Initializing hexadecimal-encoded string
hex_string = "57656c636f6d6520746f20537061726b62796578616d706c6573"
print("Original hexadecimal-encoded string:", hex_string)

# Using binascii.unhexlify()
# to convert hexadecimal-encoded string to bytes
result = binascii.unhexlify(hex_string)
print("After converting the hexadecimal-encoded string to bytes:", result)
print("Type of the converted bytes:", type(result))

Yields below output.

python convert string bytes

5. Convert String to Byte Using memoryview() Function

You can use the memoryview() function to create a memory view object from a bytes-like object. For example, you first encode the string using UTF-8 to get bytes, then create a memory view object from those bytes using the memoryview() function. Finally, you convert the memory view back to bytes using the bytes() constructor. The result will be the same bytes representation of the original string.

Keep in mind that using memoryview() function might not provide any significant advantages for simple conversions like this. This function is often used for more complex scenarios where you want to manipulate the memory directly.


# Initializing string
string = "Welcome to Sparkbyexamples"
print("Original string:", string)

# Using memoryview() function
# to convert string to bytes
byte_view = memoryview(string.encode('utf-8'))
result = bytes(byte_view)
print("After converting the string to bytes:", result)
print("Type of the converted bytes:", type(result))

# Convert string to bytes using memoryview
result = memoryview(string.encode('utf-8')).tobytes()
print("After converting the string to bytes:", result)

# Output:
# Original string: Welcome to Sparkbyexamples
# After converting the string to bytes: b'Welcome to Sparkbyexamples'
# Type of the converted bytes: <class 'bytes'>

6. Convert String to Byte Using struct.pack() Method

You can also use the struct.pack() function to convert a string to bytes. The import struct statement imports the struct module, which provides functions for working with packed binary data.

In the below example, first, initialize a string variable named string with the value "Welcome to Sparkbyexamples". Using the struct.pack() function, convert the string to bytes using the format '16s', which specifies a 16-character string (padded with null bytes if necessary). Then use the bytes() function to encode the string into bytes using the UTF-8 encoding. The resulting bytes are stored in the result variable. The converted bytes and their type are printed using the print() function.


import struct

# Initializing string
string = "Welcome to Sparkbyexamples"
print("Original string:", string)

# Using struct.pack() function
# to Convert string to bytes
result = struct.pack('16s', bytes(string, 'utf-8'))
print("After converting the string to bytes:", result)
print("Type of the converted bytes:", type(result))

# Output:
# Original string: Welcome to Sparkbyexamples
# After converting the string to bytes: b'Welcome to Spark'
# Type of the converted bytes: <class 'bytes'>

Conclusion

In this article, I have explained different methods to convert strings to bytes in Python. I have explained the use of the bytes(), encode(), binascii.unhexlify(), memoryview(), and struct.pack() functions and provided examples of how to use them.

Happy Learning !!