Home »
Python
How to Convert String to Bytes in Python
Last Updated : April 27, 2025
To convert a string into bytes in Python, you can use the built-in methods encode()
and bytes()
, each offering different levels of flexibility and ease of use.
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
test_str = "include_help"
print(type(test_str))
test_bytes = test_str.encode()
print(test_bytes)
print(type(test_bytes))
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.
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
test_str = "include_help"
test_bytes_v2 = bytes(test_str, 'utf-8')
print(type(test_bytes_v2))
print(test_bytes_v2)
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.
Exercise
Select the correct option to complete each statement about converting a string to bytes in Python.
- In Python, to convert a string to bytes, you can use the ___ method of the string object.
- The ___ method accepts an optional encoding parameter to specify how the string should be encoded into bytes.
- By default, if no encoding is specified, the ___ encoding is used when converting a string to bytes.
Advertisement
Advertisement