說我有一個4字符的字符串,並且我想將此字符串轉換爲字符數組,其中字符串中的每個字符都被轉換爲其十六進制等值。例如Python:將字符串轉換爲字節數組
str = "ABCD"
我試圖讓我的輸出是
array('B', [41, 42, 43, 44])
有沒有做到這一點的簡單方法?
說我有一個4字符的字符串,並且我想將此字符串轉換爲字符數組,其中字符串中的每個字符都被轉換爲其十六進制等值。例如Python:將字符串轉換爲字節數組
str = "ABCD"
我試圖讓我的輸出是
array('B', [41, 42, 43, 44])
有沒有做到這一點的簡單方法?
編碼功能,可以幫助你在這裏,編碼返回字符串
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])
s = "ABCD"
from array import array
a = array("B", s)
如果你想要的編碼版本(十六進制)
print map(hex, a)
只需使用bytearray()
這是一個字節列表。
Python2:
s = "ABCD"
b = bytearray()
b.extend(s)
Python3:
s = "ABCD"
b = bytearray()
b.extend(map(ord, s))
順便說一句,不要使用str
作爲變量名,因爲這是內置的。
這在3.4中被破壞:'TypeError:一個整數是必需的' – 2015-04-10 02:43:05
@KevanAhlquist我的壞。現在修復它。 – Pithikos 2015-04-13 15:29:28
對於Python 3,這看起來更清潔: 's =「ABCD」', 'b = bytearray()', 'b.extend(s.encode())' – 2016-06-15 16:53:14
獲取字節數組的另一種方法是以ascii編碼字符串:b=s.encode('ascii')
。
這對我的作品(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]
你想要什麼是不可能的,至少不會在這個具體形式。一個'B'類型的字節數組包含1個字節的整數,並且它們總是以十進制表示。 – 2012-07-24 04:50:10