字符串/二进制数据到字节
我是 Python 新手。我想将字符数组转换为字节缓冲区,即有没有办法将字符串或二进制数据的数据转换为字节缓冲区。
例如:如果 str = 'apple'
我需要 'apple'
的 buffer = bytes 值,我可以像 buffer[i]
和 < code>buffer[:j]
如果我使用 map(ord,'apple')
这会返回一个列表,但我需要一个连续缓冲区。我如何在 Python 中得到这个?
更新1:我还需要字节,因为今天它可能是字符串,但明天我可能会处理文件。
更新0:我想要以字节为单位。我可以按照 @ignacio 的建议使用字符串,但字符串不行。因为最终这将进入我的滚动哈希实现
Am new to Python. I want to convert a char array to byte buffer i.e. Is there any way to convert data which could be string or binary data to byte buffer.
Eg: if str = 'apple'
I need buffer = bytes values of 'apple'
which I can access like buffer[i]
and buffer[:j]
If i use map(ord,'apple')
this returns a list but I need a continuos buffer. How do I get this in Python ?
UPDATE 1: Also I need in bytes because today it might be strings but tomorrow I might be dealing with files.
UPDATE 0: I want it in bytes. I could have used strings as @ignacio suggests but strings just wont do. Because eventually this will go into my implementation of rolling hash
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试bytearray。这会将源字符串转换为字节数组。有一个可选的编码参数,您需要指定该参数,以防 默认编码不是当前默认的字符串编码。
例子
Try bytearray. Which will convert the source string to an array of byte. There is an optional encoding parameter which you need to specify in case if the default encoding is not the current default string encoding.
Example
您可以在 python 中使用
struct
模块。You could use
struct
module in python.