Best way to convert string to bytes in Python3

Python | Converting string to bytes: In this tutorial, we will learn about the multiple approaches to convert a string to bytes with the help of examples. By Sapna Deraje Radhakrishna Last updated : January 03, 2024

Problem statement

Given a string, we have to convert it into bytes using multiple approaches.

Converting string to bytes in Python

For this purpose, you can use two of Python's inbuilt methods encode() and bytes().

1. Convert string to bytes using encode() method

The encode() is an inbuilt method in Python that is used to encode the given string based on the specified encoding technique. The default encoding technique is UTF-8.

Syntax

The syntax of the encode() method is:

string.encode(encoding=encoding, errors=errors)

Example to convert string to bytes using encode() method

test_str = "include_help"
print(type(test_str))

test_bytes = test_str.encode()
print(test_bytes)

print(type(test_bytes))

Output

The output of the above example is:

<class 'str'>
b'include_help'
<class 'bytes'>

In Python3, the first parameter of encode() defaults to 'utf-8'. This approach is also supposedly faster because the default argument results in NULL in the C code.

2. Convert string to bytes using bytes() method

The bytes() is also an inbuilt method in Python that returns a bytes object. The method converts string objects into bytes objects.

Syntax

The syntax of the bytes() method is:

bytes(str, encoding, error)

Example to convert string to bytes using bytes() method

test_str = "include_help"

test_bytes_v2 = bytes(test_str, 'utf-8')
print(type(test_bytes_v2))

print(test_bytes_v2)

Output

The output of the above example is:

<class 'bytes'>
b'include_help'

Conclusion

Using the bytes() method/constructor gives more options than just encoding the Python string. However, for encoding a string the approach 1, is more pythonic than using a constructor, because it is more readable.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.