Java String.getBytes() 和 Python 字符串之间的行为完全相同 -> 字节?

2022-09-04 19:24:09

在我的Java代码中,我有以下代码片段:

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

我希望在python中具有完全相同的结果。我该怎么做?

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

谢谢。

编辑:

此外,拥有Python 2.x和3.x的解决方案将很有趣。


答案 1

这并不像最初看起来那么简单,因为Python在历史上将字节数组和字符串混为一谈。在Python 3中,简短的答案是

secret = "secret"
secret.encode()

但是你应该阅读Python如何处理unicode,字符串和字节。


答案 2

在python-2.7中有bytearray()

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

如果这是你要找的。