Best way to convert string to bytes in Python 3?

后端 未结 3 545
慢半拍i
慢半拍i 2020-11-22 00:14

There appear to be two different ways to convert a string to bytes, as seen in the answers to TypeError: 'str' does not support the buffer interface

Which of

3条回答
  •  半阙折子戏
    2020-11-22 01:19

    It's easier than it is thought:

    my_str = "hello world"
    my_str_as_bytes = str.encode(my_str)
    type(my_str_as_bytes) # ensure it is byte representation
    my_decoded_str = my_str_as_bytes.decode()
    type(my_decoded_str) # ensure it is string representation
    

提交回复
热议问题