Python: convert string to byte array

后端 未结 8 1512
旧时难觅i
旧时难觅i 2020-11-27 05:19

Say that I have a 4 character string, and I want to convert this string into a byte array where each character in the string is translated into its hex equivalent. e.g.

8条回答
  •  天命终不由人
    2020-11-27 05:47

    encode function can help you here, encode returns an encoded version of the string

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

    or you can use array module

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

提交回复
热议问题