Convert a String to a Byte Array in Python

Recently, I was working on a Python project where I had to send data over a network. The API required the data in byte format instead of a normal string.

That’s when I realized many beginners struggle with converting strings to byte arrays in Python. While it looks complex at first, Python actually makes this task very simple with built-in functions.

In this tutorial, I will show you three practical methods to convert a string to a byte array in Python. These are methods I have personally used in real-world projects during my 10+ years of Python development.

Methods to Convert a String to a Byte Array in Python

Before jumping into methods, let’s quickly understand why we need this conversion.

  • When working with network communication, data is transmitted as bytes.
  • If you’re handling file operations (like writing binary files), you need bytes.
  • Many cryptography libraries and APIs require byte arrays instead of strings.

So, knowing how to convert strings to byte arrays is an essential Python skill.

1 – Use Python’s bytes() Function

The first method I often use is the built-in bytes() function. It’s simple and works in most cases.

# Convert string to byte array using bytes()
text = "Hello from New York!"
byte_array = bytes(text, 'utf-8')

print("Original String:", text)
print("Converted Byte Array:", byte_array)
print("Type of Object:", type(byte_array))

You can refer to the screenshot below to see the output.

python string to bytes

In the code above, I passed the string and the encoding (‘utf-8’) to the bytes() function. The result is a byte array that you can use in file handling, APIs, or sockets.

2 – Use the bytearray() Function in Python

Another useful approach is the bytearray() function. I prefer this method when I need a mutable byte array.

# Convert string to mutable byte array using bytearray()
text = "Python is powerful!"
byte_array = bytearray(text, 'utf-8')

print("Original String:", text)
print("Converted Byte Array:", byte_array)
print("Type of Object:", type(byte_array))

# Modifying the byte array
byte_array[0] = 80  # ASCII value for 'P'
print("Modified Byte Array:", byte_array)

You can refer to the screenshot below to see the output.

string to bytes python

The advantage of bytearray() is that you can modify the contents later. This is helpful when working with binary protocols where you need to update specific bytes.

3 – Use Python’s encode() Method

The third method I use frequently is the encode() method of Python strings. It’s clean and very readable.

# Convert string to byte array using encode()
text = "Made in the USA"
byte_array = text.encode('utf-8')

print("Original String:", text)
print("Converted Byte Array:", byte_array)
print("Type of Object:", type(byte_array))

You can refer to the screenshot below to see the output.

python convert string to bytes

Here, I directly called .encode(‘utf-8’) on the string. This is my personal favorite because it’s short and easy to remember.

Choose the Right Method

Now you might be wondering: which method should I use?

  • Use bytes() if you just need a quick conversion.
  • Use bytearray() if you need to modify the byte array later.
  • Use .encode() if you want clean, readable code.

In practice, I use .encode() most often, but when working with binary file formats, I switch to bytearray().

Example – Write Bytes to a File

Let me show you a real-world example where converting a string to bytes is necessary. Suppose you want to write customer data into a binary file.

# Writing string as bytes to a file
customer_data = "Customer: John Doe, Location: California, USA"
with open("customer_data.bin", "wb") as file:
    file.write(customer_data.encode('utf-8'))

print("Data written to binary file successfully!")

You can refer to the screenshot below to see the output.

string to byte python

Here, I encoded the string into bytes before writing. If you try writing a normal string in binary mode, Python will throw an error.

Example – Send Bytes Over a Network

Another common use case is sending data over a socket connection.

import socket

# Example of sending string as bytes over a socket
server_address = ('localhost', 8080)
message = "Hello Server, this is Python!"

# Create a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    sock.connect(server_address)
    sock.sendall(message.encode('utf-8'))
    print("Message sent successfully!")
finally:
    sock.close()

In this example, I converted the string into bytes before sending it through the socket. Without this step, the sendall() function would not work.

Handle Encoding in Python

One important thing to remember is encoding. Most of the time, utf-8 is the best choice because it supports almost all characters.

But if you’re working with legacy systems in the USA, you might encounter ascii encoding. Always check the system requirements before choosing the encoding.

text = "Café in Los Angeles"
# Using UTF-8 encoding
print(text.encode('utf-8'))

# Using ASCII encoding (will raise error for é)
# print(text.encode('ascii'))

If you try encoding special characters like é with ASCII, Python will throw an error. That’s why I always recommend UTF-8 unless you have a specific reason to use something else.

Example – Convert Back from Bytes to String

Sometimes, you’ll also need to convert the byte array back to a string. This is where the .decode() method comes in handy.

# Convert byte array back to string
byte_array = b'Python Guides USA'
decoded_text = byte_array.decode('utf-8')

print("Byte Array:", byte_array)
print("Decoded String:", decoded_text)

This round-trip conversion is very common when working with APIs or databases.

Best Practices for Converting Strings to Byte Arrays in Python

Over the years, I’ve learned some best practices:

  1. Always specify encoding – don’t rely on Python defaults.
  2. Use UTF-8 unless you have a strong reason not to.
  3. Choose bytearray() if you need mutability.
  4. Test conversions when dealing with special characters.

Following these practices will save you from many headaches, especially when working with international data.

Conclusion

So those were the three easy ways to convert a string to a byte array in Python – using bytes(), bytearray(), and .encode(). Each method has its own use case, and once you practice them, you’ll know which one to pick for your project.

I personally use .encode() most of the time because it’s clean and intuitive, but when I need a mutable byte array, I switch to bytearray().

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.