簡體   English   中英

Python 字符串到字節數組並返回

[英]Python string to bytearray and back

如何將人類可讀的字符串轉換為字節數組並返回?

假設我有“Hello World”並想要一個字節數組,然后從一個字節數組轉換為同一個字符串?

您可以使用bytearray()

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


要將b_array轉換回字符串格式,請使用.decode()

for elem in b_array.decode():
    print elem

在 Python 3.6 中:

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

您可以使用數組模塊

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

在 Python >= 3.6 中,將字符串轉換為字節數組:

str.encode('utf-8')

當它是一個常量字符串時,過程可以更簡單。 例如:

b'Hello World'

在將其轉換回來時:

bytes.decode('utf-8')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM