在 Python 3 中,执行:
memoryview("this is a string")
产生错误:
TypeError: memoryview: str object does not have the buffer interface
我应该怎么做才能memoryview
接受字符串,或者我应该对我的字符串进行什么转换才能被接受memoryview
?
在 Python 3 中,执行:
memoryview("this is a string")
产生错误:
TypeError: memoryview: str object does not have the buffer interface
我应该怎么做才能memoryview
接受字符串,或者我应该对我的字符串进行什么转换才能被接受memoryview
?
在docs中,memoryview
仅适用于支持bytes
orbytearray
接口的对象。(这些是相似的类型,除了前者是只读的。)
Python 3 中的字符串不是我们可以直接操作的原始字节缓冲区,而是不可变的 Unicode 符文或字符序列。但是,可以通过使用任何受支持的字符串编码(如“utf-8”、“ascii”等)将Astr
转换为缓冲区。
memoryview(bytes("This is a string", encoding='utf-8'))
请注意,bytes()
调用必然涉及将字符串数据转换并复制到可访问的新缓冲区中memoryview
。从上一段应该可以看出,不可能直接创建一个memoryview
overstr
的数据。
考虑到该错误已经清楚地说明了问题和camflint 的答案,我只会补充一点,您可以简洁地memoryview
从字符串创建一个实例,如下所示:
memoryview( b"this is a string" )