How to Convert Python string to byte array with Examples

Published on Aug. 22, 2023, 12:16 p.m.

To convert a Python string to a byte array in Python, you can use either the encode() method or the bytearray() function. Here are examples of both methods:

  1. Using encode():
my_string = "Hello, World!"             # define a string
my_bytes = my_string.encode('utf-8')   # use encode() to convert to byte array

In this example, we define a string my_string and use the encode() method to convert it to a byte array. The encode() method takes an encoding as an argument (in this case, ‘utf-8’) and returns a byte array.

  1. Using bytearray():
my_string = "Hello, World!"               # define a string
my_bytearray = bytearray(my_string, 'utf-8')   # use bytearray() to convert to byte array

In this example, we define a string my_string and use the bytearray() function to convert it to a byte array. The bytearray() function takes two arguments: the string to convert and the encoding to use.

Note that in both cases, the resulting byte array will be immutable. If you need a mutable byte array, you can use the bytearray() function and pass in an empty byte array (with no arguments) as the source:

my_bytearray = bytearray()

In general, converting a string to a byte array can be useful when working with binary data or when communicating with a system that expects data to be in byte format.

Tags:

related content