Python: convert string to byte array

后端 未结 8 1459
旧时难觅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:58

    for python 3 it worked for what @HYRY posted. I needed it for a returned data in a dbus.array. This is the only way it worked

    s = "ABCD"
    

    from array import array

    a = array("B", s)
    
    0 讨论(0)
  • 2020-11-27 05:59

    Depending on your needs, this can be one step or two steps

    1. use encode() to convert string to bytes, immutable
    2. use bytearray() to convert bytes to bytearray, mutable
    
    s="ABCD"
    encoded=s.encode('utf-8')
    array=bytearray(encoded)
    

    The following validation is done in Python 3.7

    >>> s="ABCD"
    >>> encoded=s.encode('utf-8')
    >>> encoded
    b'ABCD'
    >>> array=bytearray(encoded)
    >>> array
    bytearray(b'ABCD')
    
    0 讨论(0)
提交回复
热议问题