In Python 3, executing:
memoryview("this is a string")
produces the error:
TypeError: memoryview: str object does not have the buffer interface
What should I do in order to make memoryview accept strings or what transformation should I do to my strings in order to be accepted by memoryview?
From the docs, memoryview works only over objects which support the bytes or bytearray interface. (These are similar types except the former is read-only.)
Strings in Python 3 are not raw byte buffers we can directly manipulate, rather they are immutable sequences of Unicode runes or characters. A str can be converted to a buffer, though, by encoding it with any of the supported string encodings like 'utf-8', 'ascii', etc.
memoryview(bytes("This is a string", encoding='utf-8'))
Note that the bytes() call necessarily involves converting and copying the string data into a new buffer accessible to memoryview. As should be evident from the preceding paragraph, is not possible to directly create a memoryview over the str's data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With