Python字符串到bytearray和返回

时间:2022-08-01 18:26:10

How can I convert a human readable string to a bytearray and back?

如何将人类可读的字符串转换为bytearray并返回?

Say I have "Hello World" and want a bytearray and then from a bytearray to the same string?

假设我有“Hello World”并想要一个bytearray然后从bytearray到同一个字符串?

3 个解决方案

#1


5  

You can use bytearray():

你可以使用bytearray():

b_array = bytearray('yoyo')
for elem in b_array:
    print elem


To convert b_array back to string format use .decode():

要将b_array转换回字符串格式,请使用.decode():

for elem in b_array.decode():
    print elem

#2


2  

In Python 3.6:

在Python 3.6中:

b_array = bytearray('yoyo'.encode())
for elem in b_array:
    print (elem)

#3


0  

You can use the array module

您可以使用阵列模块

from array import array
s = "hello world"
s = array('B', s)
print s
s.tostring()
#or s = s.tostring()

#1


5  

You can use bytearray():

你可以使用bytearray():

b_array = bytearray('yoyo')
for elem in b_array:
    print elem


To convert b_array back to string format use .decode():

要将b_array转换回字符串格式,请使用.decode():

for elem in b_array.decode():
    print elem

#2


2  

In Python 3.6:

在Python 3.6中:

b_array = bytearray('yoyo'.encode())
for elem in b_array:
    print (elem)

#3


0  

You can use the array module

您可以使用阵列模块

from array import array
s = "hello world"
s = array('B', s)
print s
s.tostring()
#or s = s.tostring()