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
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'>
Discussions

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 convert bytes to string in python?
Try this: line = ser.readline().strip() values = line.decode('ascii').split(',') a, b, c = [int(s) for s in values] The call to .strip() removes the trailing newline. The call .decode('ascii') converts the raw bytes to a string. .split(',') splits the string on commas. Finally the call [int(s) for s in value] is called a list comprehension, and produces a list of integers. More on reddit.com
🌐 r/Python
3
1
February 8, 2016
How do i make a bytes object convert to a formatted string.
That's its representation. Print the string to see it formatted: >>> b = b"\tHello\nWorld" >>> s = b.decode() >>> s '\tHello\nWorld' >>> print(s) Hello World More on reddit.com
🌐 r/learnpython
5
1
February 14, 2025
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-convert-string-to-bytes
Convert String to bytes-Python - GeeksforGeeks
For example, given the string "Hello", these methods can convert it into a byte representation like b'Hello'. Let’s explore different methods to accomplish this efficiently. encode() method is a very straightforward way to convert a string ...
Published: July 11, 2025
🌐
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.

🌐
Medium
medium.com › data-science › byte-string-unicode-string-raw-string-a-guide-to-all-strings-in-python-684c4c4960ba
Byte string, Unicode string, Raw string — A Guide to all strings in Python | by Guangyuan(Frank) Li | TDS Archive | Medium
November 23, 2022 - UTF-8 is way more popular than UTF-16 so in this article and for most of your work as they are compatible with the old original ASCII standard (one character can be represented using one byte), understanding the UTF-8 is enough. See the “UTF-8” table for full information. With the basic concepts understood, let’s cover some practical coding tips in Python. In Python3, the default string is called Unicode string (u string), you can understand them as human-readable characters. As explained above, you can encode them to the byte string (b string), and the byte string can be decoded back to the Unicode string.
Find elsewhere
🌐
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).
🌐
Mimo
mimo.org › glossary › python › bytes
Mimo: The coding platform you need to learn Web Development, Python, and more.
You use them when dealing with ... data types helps prevent encoding bugs when mixing unicode and text encodings. ... A bytes object is defined by prefixing a string literal with a b....
🌐
Real Python
realpython.com › python-bytes
Bytes Objects: Handling Binary Data in Python – Real Python
March 5, 2025 - The difference between bytes and bytearray is that bytes objects are read-only, while bytearray objects are mutable. You convert a Python string to bytes using the str.encode() method, the bytes() function, or the codecs module.
🌐
DataCamp
datacamp.com › tutorial › bytes-to-string-python
How to Convert Bytes to String in Python | DataCamp
June 12, 2024 - The first 128 UTF-8 codes match the ASCII codes, which is why the bytes object data is decoded to the string "DataCamp" in the example above. However, Unicode contains nearly 150,000 characters. UTF-8 encodes all the non-ASCII characters in Unicode using two or more bytes. ... The bytes object contains two bytes: the integers 195 and 169. Python displays the hexadecimal representation of these bytes.
🌐
Theunterminatedstring
theunterminatedstring.com › python-bits-and-bytes
Python Bits and Bytes - The Unterminated String
May 19, 2018 - The str object has an encode() method to return the bytes representation of the string.
🌐
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')
🌐
freeCodeCamp
freecodecamp.org › news › python-bytes-to-string-how-to-convert-a-bytestring
Python Bytes to String – How to Convert a Bytestring
April 10, 2023 - This is because Python 3.x uses Unicode encoding for strings by default, whereas previous versions of Python used ASCII encoding. So when working with bytestrings in Python 3.x, it's important to be aware of the encoding used and to properly encode and decode data as needed.
🌐
Keploy
keploy.io › home › community › what is a python bytestring?
Mastering Python Bytestrings: A Beginner's Guide
July 24, 2025 - Here, we use the bytes() constructor to encode the string into a bytes object using the built-in bytes() constructor. It is shown in the snippet below. ... In the above code, we are telling Python to convert the string “Hello” to a bytestring ...
🌐
Sentry
sentry.io › sentry answers › python › convert bytes to a string in python
Convert bytes to a string in Python | Sentry
March 15, 2023 - my_ascii_string = my_byte_sequence.decode("ascii") Note that if the byte sequence contains invalid characters for the specified encoding, a UnicodeDecodeError will be raised. In that case, you can try a different encoding. ... Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski. SEE EPISODES · Change the size of figures drawn with Matplotlib in Python
🌐
Online String Tools
onlinestringtools.com › convert-string-to-bytes
Convert a String to Bytes – Online String Tools
Instant Copy-to-clipboardCopy the string to clipboard with a single click. ... If a byte is less than 0xf, make it 0x0f.
🌐
The Python Coding Stack
thepythoncodingstack.com › the python coding stack › `bytes`: the lesser-known python built-in sequence • and understanding utf-8 encoding
`bytes`: The Lesser-Known Python Built-In Sequence • And Understanding UTF-8 Encoding
July 15, 2025 - Each character in the original string is converted to its ASCII code. You can find the ASCII codes for all the characters here. ASCII is a 7-bit encoding. Therefore, it contains 128 characters, but not all of them are printable characters. Several ASCII codes are now obsolete. And since there are only 128 ASCII characters, and their codes range from 0 to 127, they all fit within one byte of data (which has eight bits).
🌐
Reddit
reddit.com › r/learnpython › how do i make a bytes object convert to a formatted string.
r/learnpython on Reddit: How do i make a bytes object convert to a formatted string.
February 14, 2025 -

I have a variable that is a bytes object that is a representation of formatted text.

 Byte_to_string = b”\tHello\nWorld”

I want to convert the object to a formatted string.

“      Hello
 World”

However what i am getting is ”\tHello\nWorld”.

What am i missing? How can i fix this?

🌐
Python.org
discuss.python.org › python help
Converting bytes to string to bytes - Python Help - Discussions on Python.org
October 28, 2021 - Here’s what I’m trying: from ... salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) converting the signature using base64 encode and decode methods to string....