Python 如何将字符串转换为字节数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4490901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert string to byte arrays?
提问by Martin
How can I convert a string to its byte value? I have a string "hello"and I want to change is to something like "/x68...".
如何将字符串转换为其字节值?我有一个字符串"hello",我想更改为类似"/x68...".
回答by kindall
Python 2.6 and later have a bytearraytype which may be what you're looking for. Unlike strings, it is mutable, i.e., you can change individual bytes "in place" rather than having to create a whole new string. It has a nice mix of the features of lists and strings. And it also makes your intent clear, that you are working with arbitrary bytes rather than text.
Python 2.6 及更高版本有一个bytearray类型,这可能是您正在寻找的。与字符串不同,它是可变的,即您可以“就地”更改单个字节,而不必创建一个全新的字符串。它很好地结合了列表和字符串的特性。它还明确了您的意图,您正在使用任意字节而不是文本。
回答by barti_ddu
If you want to get hexadecimal string representation you could do:
如果你想获得十六进制字符串表示,你可以这样做:
"hello".encode("hex") # '68656c6c6f'
And to meet your reference representation (don't take it seriously, guess this is not what you really want):
并满足您的参考表示(不要当真,猜测这不是您真正想要的):
"".join(["/x%02x" % ord(c) for c in "hello"]) # '/x68/x65/x6c/x6c/x6f'
回答by Mark Tolonen
Perhaps you want this (Python 2):
也许你想要这个(Python 2):
>>> map(ord,'hello')
[104, 101, 108, 108, 111]
For a Unicode string this would return Unicode code points:
对于 Unicode 字符串,这将返回 Unicode 代码点:
>>> map(ord,u'Hello, 马克')
[72, 101, 108, 108, 111, 44, 32, 39532, 20811]
But encode it to get byte values for the encoding:
但是对其进行编码以获取编码的字节值:
>>> map(ord,u'Hello, 马克'.encode('chinese'))
[72, 101, 108, 108, 111, 44, 32, 194, 237, 191, 203]
>>> map(ord,u'Hello, 马克'.encode('utf8'))
[72, 101, 108, 108, 111, 44, 32, 233, 169, 172, 229, 133, 139]

