简体   繁体   中英

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

Python 2.6 and later have a bytearray type which may be what you're looking for. 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):

>>> map(ord,'hello')
[104, 101, 108, 108, 111]

For a Unicode string this would return Unicode code points:

>>> 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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