Python Convert String to Byte

后端 未结 2 1087
不知归路
不知归路 2021-01-19 10:52

I am trying to do some serial input and output operations, and one of those is to send an 8x8 array to an external device (Arduino). The pySerial library requires that the i

相关标签:
2条回答
  • 2021-01-19 10:57

    To transform a unicode string to a byte string in Python do this:

    >>> 'foo'.encode('utf_8')
    b'foo'
    

    To transform a byte string to a unicode string:

    >>> b'foo'.decode('utf_8')
    'foo'
    

    See encode and decode in the Standard library.

    The available encodings are documented in this table. Commonly used ones are utf_8, utf_8_sig, ascii, latin_1 and cp1252. See UTF-8, BOM, ASCII, Latin-1 and Windows-1252 at Wikipedia.

    Helpful for debbugging can be raw_unicode_escape. See this table.

    0 讨论(0)
  • 2021-01-19 11:07

    in Python 3.x, You can use bytes and str like below.

    >>> bytes('foo'.encode())
    b'foo'
    
    >>> a = bytes('foo'.encode())
    >>> str(a.decode())
    'foo'
    
    0 讨论(0)
提交回复
热议问题