简体   繁体   English

如何将字符串转换为字节数组?

[英]How to convert string to byte arrays?

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..."

Python 2.6 and later have a bytearray type which may be what you're looking for. Python 2.6及更高版本有一个bytearray类型,可能是你正在寻找的。 Unlike strings, it is mutable, ie, 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. 它也使你的意图清晰,你正在使用任意字节而不是文本。

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]

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM