How to convert between bytes and strings in Python 3?

后端 未结 4 1831
囚心锁ツ
囚心锁ツ 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:15

    In python3, there is a bytes() method that is in the same format as encode().

    str1 = b'hello world'
    str2 = bytes("hello world", encoding="UTF-8")
    print(str1 == str2) # Returns True
    

    I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

提交回复
热议问题