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')
Which method is more Pythonic?
See Convert bytes to a string for the other way around.
If you look at the docs for
bytes, it points you tobytearray:So
bytescan do much more than just encode a string. It’s Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.For encoding a string, I think that
some_string.encode(encoding)is more Pythonic than using the constructor, because it is the most self documenting — "take this string and encode it with this encoding" is clearer thanbytes(some_string, encoding)— there is no explicit verb when you use the constructor.I checked the Python source. If you pass a unicode string to
bytesusing CPython, it calls PyUnicode_AsEncodedString, which is the implementation ofencode; so you’re just skipping a level of indirection if you callencodeyourself.Also, see Serdalis’ comment —
unicode_string.encode(encoding)is also more Pythonic because its inverse isbyte_string.decode(encoding)and symmetry is nice.