深度阅读

How to Convert Python string to byte array with Examples

作者
作者
2023年08月22日
更新时间
13.59 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。