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
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.
getbytes() function in java is used to convert a string into a sequence of bytes and returns an array of bytes.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With