2012-07-24 33 views
35

說我有一個4字符的字符串,並且我想將此字符串轉換爲字符數組,其中字符串中的每個字符都被轉換爲其十六進制等值。例如Python:將字符串轉換爲字節數組

str = "ABCD" 

我試圖讓我的輸出是

array('B', [41, 42, 43, 44]) 

有沒有做到這一點的簡單方法?

+3

你想要什麼是不可能的,至少不會在這個具體形式。一個'B'類型的字節數組包含1個字節的整數,並且它們總是以十進制表示。 – 2012-07-24 04:50:10

回答

34

編碼功能,可以幫助你在這裏,編碼返回字符串

In [44]: str = "ABCD" 

In [45]: [elem.encode("hex") for elem in str] 
Out[45]: ['41', '42', '43', '44'] 

,或者您可以使用陣列模塊

In [49]: import array 

In [50]: print array.array('B', "ABCD") 
array('B', [65, 66, 67, 68]) 
+0

但是,正如你所看到的,數組模塊給出了字符串元素的ascii值,這與您的預期輸出不匹配 – avasal 2012-07-24 04:51:01

+0

謝謝。這些想法給我足夠的工作! – Alex 2012-07-24 04:59:33

+0

爲什麼不使用'map'? – pradyunsg 2013-05-04 12:14:17

2
s = "ABCD" 
from array import array 
a = array("B", s) 

如果你想要的編碼版本(十六進制)

print map(hex, a) 
22

只需使用bytearray()這是一個字節列表。

Python2:

s = "ABCD" 
b = bytearray() 
b.extend(s) 

Python3:

s = "ABCD" 
b = bytearray() 
b.extend(map(ord, s)) 

順便說一句,不要使用str作爲變量名,因爲這是內置的。

+0

這在3.4中被破壞:'TypeError:一個整數是必需的' – 2015-04-10 02:43:05

+0

@KevanAhlquist我的壞。現在修復它。 – Pithikos 2015-04-13 15:29:28

+0

對於Python 3,這看起來更清潔: 's =「ABCD」', 'b = bytearray()', 'b.extend(s.encode())' – 2016-06-15 16:53:14

3

獲取字節數組的另一種方法是以ascii編碼字符串:b=s.encode('ascii')

4

這對我的作品(Python的2)

s = "ABCD" 
b = bytearray(s) 

# if your print whole b, it still displays it as if its original string 
print b 

# but print first item from the array to see byte value 
print b[0] 

參考: http://www.dotnetperls.com/bytes-python

相關問題