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
[Python 3] Understanding the difference between byte string and strings.
The bytes that python is using under the covers aren't necessarily the bytes that you want. If I want to put the word café on my website then I probably need the bytes 0x63 0x61 0x66 0xc3 0xa9. But the bytes that python currently uses to represent the string 'café' under the covers is actually 0x63 0x61 0x66 0xe9. I can't use the same bytes that python uses because python doesn't use the bytes I need. Python chooses to represent things using a certain pattern of bytes for it's own reasons, but there are many different ways to express the same thing using bytes. You may wish to (or be forced to) use a different one than what python picks. bytes objects allow you to do that. By not having your code rely on the way that python represents things in bytes, it makes it possible for python to change the representation if it finds a better way. Dictionaries were recently updated to make them significantly smaller, but in order to do this python had to change the byte representation of dictionaries. They would have broken other code that relied on that representation. More on reddit.com
🌐 r/learnpython
8
7
October 20, 2018
🌐
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
🌐
Real Python
realpython.com › convert-python-bytes-to-strings
How to Convert Bytes to Strings in Python – Real Python
October 5, 2025 - It’s important to be able to manage and handle bytes where they come up. Sometimes they need to be converted into strings for further use or comprehensibility. By the end of this guide, you’ll be able to convert Python bytes to strings so that you can work with byte data in a human-readable format.
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-hex-string-to-bytes-in-python
Convert Hex String to Bytes in Python - GeeksforGeeks
July 23, 2025 - You can convert a hexadecimal string into bytes using list comprehension in a single line by splitting the hex string into pairs of characters, converting each pair to its decimal equivalent and then converting the result into a bytes object.
Find elsewhere
🌐
Python documentation
docs.python.org › 3 › library › stdtypes.html
Built-in Types — Python 3.14.5rc1 documentation
If neither encoding nor errors is given, str(object) returns type(object).__str__(object), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object). If at least one of encoding or errors is given, object should be a bytes-like object (e.g.
🌐
Kodeclik
kodeclik.com › python-convert-string-to-bytes
Python Convert String to Bytes
October 16, 2024 - There are two ways to convert a Python string to the underlying array of bytes used to store it. 1. Use the encode method on the string. 2. Use the bytes function that can be applied on the given string.
🌐
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).
🌐
JanBask Training
janbasktraining.com › community › python-python › convert-bytes-to-a-string-in-python-3
Convert bytes to a string in Python 3 | JanBask Training Community
May 25, 2025 - In Python 3, strings (type str) are Unicode by default, while bytes are sequences of raw 8-bit values. To convert bytes to a string, you need to decode them using the correct character encoding—usually UTF-8.
🌐
Edureka Community
edureka.co › community › 101271 › best-way-to-convert-string-to-bytes-in-python
Best way to convert string to bytes in Python
Host '172.31.27.232' is blocked because of many connection errors; unblock with 'mariadb-admin flush-hosts'
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-encode-decode
Python String Encode and Decode: Complete Guide | DigitalOcean
August 3, 2022 - Please enter string data: aåb∫cçd∂e´´´ƒg©1¡ Encoded bytes = b'a\xc3\xa5b\xe2\x88\xabc\xc3\xa7d\xe2\x88\x82e\xc2\xb4\xc2\xb4\xc2\xb4\xc6\x92g\xc2\xa91\xc2\xa1' Decoded String = aåb∫cçd∂e´´´ƒg©1¡ str_original equals str_decoded = True · You can checkout complete python script and more Python examples from our GitHub Repository.
🌐
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....
🌐
FavTutor
favtutor.com › blogs › bytes-to-string-python
4 Methods to Convert Bytes to String in Python (with code)
February 8, 2023 - This function decodes different types of encoding of strings to a normal string. The decode() function in python can be used to take our data encoded in bytes format and decode it to convert the data to string format.
🌐
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 - We specify the encoding format as utf-8 using the encoding parameter. Finally, we print the resulting string to the console. We can also use the bytes() constructor, a built-in Python function used to create a new bytes object.
🌐
Real Python
realpython.com › python-bytes
Bytes Objects: Handling Binary Data in Python – Real Python
January 20, 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.
🌐
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 means the best option in this case is to use utf-8. If you want a different format, the solution is to ignore special characters, but still, there are chances of losing data. Therefore, many businesses often hire Python developers who are experienced and know all data handling strategies. If you want to reverse the process from bytes to a string, use the decode method.
🌐
Luasoftware
code.luasoftware.com › tutorials › python › python-string-to-bytes
Python 3 String to Bytes
June 7, 2019 - Related articlesPython Encryption Using TinkPython Only Allow Single Instance to Run (or Kill Previous Instance)Python Asyncio Graceful Shutdown (Interrupt Sleep)Simple Guide to Subprocess (launch another python script)Simple Guide to Python AsyncioSimple Guide to Python MultiprocessingPython FTP: List Files in Directory and DownloadGoogle OAuth2 Build Google REST Api Service on LocalSimple Guide to Python ThreadingPython 3.x: Threading vs Multiprocessing vs AsyncioPython 3.x Float Rounding Error (Decimal)Complete Guide to Python Variable Arguments (varargs, args, kwargs)Setup and Access Googl
🌐
PythonHow
pythonhow.com › how › convert-bytes-to-a-string
Here is how to convert bytes to a string in Python
If you try to use it on a normal string, you'll get an error. To avoid this, you can use the encode() method to convert a string to a byte string first, then use decode() to convert it back to a string.