Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to convert string to bytes in Python 3

TypeError: 'str' does not support the buffer interface suggests two possible methods to convert a string to bytes:

b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')

What are the differences between them? Which one should I opt for and why?


See Convert bytes to a string in Python 3 for the other way around.

Answer*

Draft saved
Draft discarded
Cancel
7
  • 139
    +1 for having a good argument and quotes from the python docs. Also unicode_string.encode(encoding) matches nicely with bytearray.decode(encoding) when you want your string back. Commented Sep 28, 2011 at 15:30
  • 12
    bytearray is used when you need a mutable object. You don't need it for simple strbytes conversions. Commented Sep 28, 2011 at 15:41
  • 9
    @EugeneHomyakov This has nothing to do with bytearray except that the docs for bytes don't give details, they just say "this is an immutable version of bytearray" so I have to quote from there. Commented Sep 28, 2011 at 15:43
  • 1
    Just a cautionary note from Python in a Nutshell about bytes: Avoid using the bytes type as a function with an integer argument. In v2 this returns the integer converted to a (byte)string because bytes is an alias for str, while in v3 it returns a bytestring containing the given number of null characters. So, for example, instead of the v3 expression bytes(6), use the equivalent b'\x00'*6, which seamlessly works the same way in each version. Commented Aug 20, 2017 at 10:09
  • 5
    Just a note, that if you are trying to convert binary data to a string, you'll most likely need to use something like byte_string.decode('latin-1') as utf-8 doesn't cover the entire range 0x00 to 0xFF (0-255), check out the python docs for more info. Commented Jul 10, 2019 at 14:25

lang-py

AltStyle によって変換されたページ (->オリジナル) /