14

In my Java code I have the following snippet :

String secret = "secret";
byte[] thebytes = secret.getBytes();

I would like to have exactly the same result in python. How can I do that ?

secret = 'secret'
thebytes = ??? ??? ???

Thanks.

EDIT:

In addition, it will be interesting to have the solution for Python 2.x and 3.x

4
  • What's the result of secret.getBytes()? Commented Feb 21, 2012 at 10:17
  • 1
    Which version of Python? String handling was dramatically updated in Python 3 to make Unicode sensible. Commented Feb 21, 2012 at 10:20
  • Unicode not needed. But I think that it will be interesting if there's a solution :-) Commented Feb 21, 2012 at 10:26
  • In Python 2.x, str is bytes. The str type represents bytes. It contains bytes. How would you like to have the bytes, what do you want to do with them? Commented Feb 21, 2012 at 10:40

3 Answers 3

10

This is not as simple as it might first seem, because Python has historically conflated byte arrays and strings. The short answer, in Python 3, is

secret = "secret"
secret.encode()

But you should read up on how Python deals with unicode, strings and bytes.

Sign up to request clarification or add additional context in comments.

1 Comment

str in Python 2.x is a string of bytes. If you want their byte value as an integer then map(ord, secret), as @Linus said.
8

In python-2.7 there's bytearray():

>>> s = 'secret'
>>> b = bytearray(s)
>>> for i in b:
...    print i
115
101
99
114
101
116

If this is what you're looking for.

Comments

4

I'm not sure about exactly the same, since Python doesn't have byte, but this might do the trick:

bytes = [ord(c) for c in "secret"] # => [115, 101, 99, 114, 101, 116]

Or using map, as katrielalex suggested, just because it's pretty:

bytes = map(ord, "secret") # => [115, 101, 99, 114, 101, 116]

2 Comments

map(ord, "secret") not showing as you display in above sample array. It shows as <map object at 0x0000026298F0F940>. Please guide me how to get byte array
SUPER DUPER LATE but here it is... list(map(foo, iterable))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.