If you look at the docs for bytes, it points you to bytearray:

bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.

For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.

I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself.

Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice.

Answer from agf on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how do i convert a string to bytes?
r/learnpython on Reddit: How do I convert a string to bytes?
August 8, 2023 -

Suppose I something like

s = "GW\x25\001"

How do I convert that string to bytes, interpreting the backslashes as escapes? In other words, the resulting byte array should be of length 4.

UPDATE: Hmmm, I was taking the string from sys.argv[1], which seems to complicate things and not make it turn out as expected. So I'm still not sure what the answer is.

Python str vs bytes Jul 2, 2024
r/learnprogramming
2y ago
How to divide encoded string by number of bytes? Apr 9, 2020
r/learnpython
6y ago
How to read string to bytes without encoding? May 9, 2019
r/learnpython
7y ago
TypeError: can't concat str to bytes Dec 12, 2021
r/learnpython
4y ago
Bytes and bytesarray. Aug 9, 2015
r/Python
11y ago
More results from reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-string-to-bytes
Convert String to bytes-Python - GeeksforGeeks
It turns a string into a sequence of bytes using a specified encoding format (default is UTF-8). ... Explanation: encode() method converts a string to bytes using the specified encoding, here "utf-8", allowing the string to be processed as binary ...
Published: July 11, 2025
Discussions

How to convert string to bytes in Python 3 - Stack Overflow
TypeError: 'str' does not support the buffer interface suggests two possible methods to convert a string to bytes: b = bytes(mystring, 'utf-8') b = mystring.encode('utf-8') What are the More on stackoverflow.com
🌐 stackoverflow.com
Converting bytes to string to bytes
How can I convert bytes to string to bytes back? Here’s what I’m trying: from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding message = b"A message I want to sign" signature = private_key.sign( message, padding.PSS( mgf=padding... More on discuss.python.org
🌐 discuss.python.org
8
0
October 28, 2021
How do I convert a string to bytes?
Or use the bytes() builtin function . An example: x = "abc☺xyz" print(x) y = bytes(x, encoding="utf-8") print(y) More on reddit.com
🌐 r/learnpython
15
6
August 8, 2023
How to concatenate byte strings in Python 3
Python 3.5 will re-introduce some restricted %-formatting, for bytestrings. With Python 3 and the split between str and bytes , one small but important area of programming became slightly more difficult, and much more painful -- wire format protocols https://www.python.org/dev/peps/pep-0461/ More on reddit.com
🌐 r/Python
7
0
February 28, 2015
People also ask

What is the default encoding for string to byte conversion in Python?
Python uses 'utf-8' as the default encoding when converting strings to bytes unless you choose a different encoding.
🌐
wscubetech.com
wscubetech.com › resources › python › programs › string-to-bytes
String to Bytes in Python (6 Programs With Output)
How can I convert a string to bytes in Python?
To convert a string to bytes in Python, you can use the encode() method. For example, your_string.encode('utf-8') will change the string into bytes.
🌐
wscubetech.com
wscubetech.com › resources › python › programs › string-to-bytes
String to Bytes in Python (6 Programs With Output)
How can I convert bytes back to a string in Python?
To convert bytes back to a string, use the decode() method. For example, my_bytes.decode('utf-8') will get you the original string.
🌐
wscubetech.com
wscubetech.com › resources › python › programs › string-to-bytes
String to Bytes in Python (6 Programs With Output)
🌐
DataCamp
datacamp.com › tutorial › string-to-bytes-conversion
How to Convert String to Bytes in Python | DataCamp
June 5, 2024 - In Python, use the .encode() method on a string to convert it into bytes, optionally specifying the desired encoding (UTF-8 by default).
Top answer
1 of 5
894

If you look at the docs for bytes, it points you to bytearray:

bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.

For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.

I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself.

Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice.

2 of 5
735

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = my_str.encode()
print(type(my_str_as_bytes)) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
print(type(my_decoded_str)) # ensure it is string representation

you can verify by printing the types. Refer to output below.

<class 'bytes'>
<class 'str'>
🌐
Sentry
sentry.io › sentry answers › python › convert a string to bytes in python
Convert a String to Bytes in Python with encode() | Sentry
September 10, 2026 - Use the str.encode() method or the bytes() constructor to convert a Python string into a bytes object, with UTF-8 as the default character encoding
🌐
Jeremy Morgan
jeremymorgan.com › python › how-to-convert-string-to-bytes-in-python
How to Convert String to Bytes in Python - Jeremy Morgan's
December 8, 2023 - The most common way to convert a string into bytes is by using the encode() method. This method takes a string and an encoding scheme as arguments and returns a byte object that represents the encoded string.
Find elsewhere
🌐
Flexiple
flexiple.com › python › python-string-to-bytes
How to convert Python string to bytes? | Flexiple Tutorials | Python - Flexiple
Note: This method converts objects into immutable bytes, if you are looking for a mutable method you can use the bytearray() method. The encode() method is the most commonly used and recommended method to convert Python strings to bytes.
🌐
Edureka Community
edureka.co › home › community › categories › python › best way to convert string to bytes in python
Best way to convert string to bytes in Python | Edureka Community
December 28, 2020 - There appear to be two different ways to convert a string to bytes, Which of these methods would be better ... 'utf-8') b = mystring.encode('utf-8')
🌐
Educative
educative.io › answers › how-to-convert-strings-to-bytes-in-python
How to convert strings to bytes in Python
We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument.
🌐
WsCube Tech
wscubetech.com › resources › python › programs › string-to-bytes
String to Bytes in Python (6 Programs With Output)
October 29, 2025 - Discover 6 simple methods to convert Python strings to bytes. Our step-by-step guide offers clear examples with output and explanation. Learn now!
🌐
Pierian Training
pieriantraining.com › home › how to convert a string to bytes using python
Understanding String and Bytes Conversions in Python
April 27, 2023 - In this example, we first define a variable called hello with a string value ‘Hello World’. We then use the encode() method on it with no arguments specified because we want to use the default encoding scheme (UTF-8). Finally, we print out ...
🌐
DEV Community
dev.to › eric_walter › how-to-convert-a-string-to-bytes-in-python-n27
How to Convert a String to Bytes in Python - DEV Community
July 10, 2025 - This conversion is important because of the following use cases where bytes are mandatory: Saving data in binary files, like images, logs, or zip files · Sending data over the network, like in APIs or sockets · Using encryption or compression tools to shrink data ... This is the reason many businesses, especially tech startups, hire Python developers who are proficient in handling such data transformations. Here are some simple and beginner-friendly methods to convert strings to bytes in Python:
🌐
Programiz
programiz.com › python-programming › methods › built-in › bytes
Python bytes()
Online Python Online JavaScript Online SQL Online Java Online HTML Online C Online C++ Online C# Online PHP Online Swift Online Kotlin Online TypeScript Online Go Online Rust Online Scala Online Dart Online R Online Ruby ... The bytes() method returns an immutable bytes object initialized with the given size and data. ... # convert string to bytes byte_message = bytes(message, 'utf-8') print(byte_message) # Output: b'Python is fun'
🌐
Analytics Vidhya
analyticsvidhya.com › home › 7 ways to convert string to bytes in python
7 Ways to Convert String to Bytes in Python - Analytics Vidhya
February 7, 2024 - This process is essential in Python for various reasons, including data encryption, network communication, and file handling. In this article, we will explore the 7 methods of converting strings to bytes in Python, its importance, and its benefits.
🌐
Python Guides
pythonguides.com › convert-string-to-bytes-in-python
How to Convert String to Bytes in Python?
April 7, 2025 - Read How to Print Strings and Variables in Python? The simplest and most widely used approach to convert a string to bytes is using the encode() method.
🌐
AskPython
askpython.com › python › string › python-string-bytes-conversion
Python String to bytes, bytes to String - AskPython
February 16, 2023 - Python’s CPython library provides us with bytes() function to convert String to bytes.
🌐
Python Guides
pythonguides.com › python-string-to-byte-array
Convert a String to a Byte Array in Python
September 23, 2025 - Learn three easy methods to convert a string to a byte array in Python using bytes(), bytearray(), and encode(). Includes examples and best practices.
🌐
w3resource
w3resource.com › python › python-bytes.php
Python Bytes, Bytearray
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
🌐
Python.org
discuss.python.org › python help
Converting bytes to string to bytes - Python Help - Discussions on Python.org
October 28, 2021 - How can I convert bytes to string to bytes back? Here’s what I’m trying: from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding message = b"A message I want to sign" signature = private_key.sign( message, padding.PSS( mgf=padding...