0

I need to extract the bytes from a string variable in Python (v 2.6) to pass it as a parameter for another function which expects a byte array.

Here is an example of what I have:

myStr = "some string"

What I need is something equivalent of a byte array but from the myStr variable.:

bytes = b'some string'

I tried using myStr.encode(), but I received a TypeError from the target function.

Any help is much appreciated.

Byob
  • 452
  • 6
  • 11

2 Answers2

1

In Python 2 the str type is already encoded.

Could something like this serve you?

>>>import array
>>>s = array.array('b', myStr)
array('b', [115, 111, 109, 101, 32, 115, 116, 114, 105, 110, 103])
Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
  • I tried this approach and it worked. All I needed was to create an array with the ASCII values. Thanks for your help! – Byob Feb 17 '14 at 13:35
1

do you just need a list of the ascii values of the string?

 >>> map(ord, "some string")
 [115, 111, 109, 101, 32, 115, 116, 114, 105, 110, 103]
eduffy
  • 39,140
  • 13
  • 95
  • 92