How to convert between bytes and strings in Python 3?

后端 未结 4 1845
囚心锁ツ
囚心锁ツ 2020-11-28 04:25

This is a Python 101 type question, but it had me baffled for a while when I tried to use a package that seemed to convert my string input into bytes.

As you will s

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 05:05

    The 'mangler' in the above code sample was doing the equivalent of this:

    bytesThing = stringThing.encode(encoding='UTF-8')
    

    There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

    newStringThing = bytesThing.decode(encoding='UTF-8')
    

    When we do this, the original string is recovered.

    Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

提交回复
热议问题