When encountering the error "TypeError: 'str' does not support the buffer interface," you have two options to convert a string to bytes:
Choosing the More Pythonic Method
The Python documentation for the bytes type suggests using bytearray as the preferred method to initialize an array of bytes from a string:
bytearray([source[, encoding[, errors]]])
With this in mind, since bytes can perform various tasks beyond encoding strings, it makes sense for the constructor to accept different types of source parameters.
For string encoding specifically, using some_string.encode(encoding) is more Pythonic than bytes(some_string, encoding):
Furthermore, unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding), maintaining symmetry.
Optimizing Performance with CPython
If using CPython, passing a unicode string to bytes directly calls PyUnicode_AsEncodedString, which is the underlying implementation of encode. Therefore, calling encode yourself eliminates an unnecessary level of indirection and potentially improves performance.
The above is the detailed content of How to Efficiently Convert Strings to Bytes in Python 3?. For more information, please follow other related articles on the PHP Chinese website!