Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exactly the same behavior between Java String.getBytes() and Python string -> bytes?

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

like image 511
Sandro Munda Avatar asked Feb 21 '12 10:02

Sandro Munda


People also ask

What is the difference between string and bytes in Python?

Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.

What does getBytes do in Java?

getbytes() function in java is used to convert a string into a sequence of bytes and returns an array of bytes.

What is getBytes ()?

The method getBytes() encodes a String into a byte array using the platform's default charset if no argument is passed. We can pass a specific Charset to be used in the encoding process, either as a String object or a String object.

What is byte sequence in Python?

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer. On the other hand, a character string, often just called a "string", is a sequence of characters.


2 Answers

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.

like image 75
Rik Poggi Avatar answered Oct 01 '22 04:10

Rik Poggi


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.

like image 22
Katriel Avatar answered Oct 01 '22 04:10

Katriel