我是python的nebie。我有一个接受字符串的java方法,将字符串转换为字节数组并返回字节数组。该方法看起来像这样。java的getByte()在python中相当于
private static byte[] convert(String str) {
byte[] byteArray = str.getBytes();
return byteArray;
}
convert("sr_shah")
结果在一个字节数组这样 115 114 95 115 104 97 104
。在使用Charset.defaultCharset()
我知道我的机器的默认charectorset是windows-1252
。
现在我需要在Python中创建上述方法的精确等价物。我现在面临的问题是将字符串转换为bytearray。我无法在Python中获得java的getBytes()等价物。我在互联网上搜索,从stackoverflow的以前的帖子转换字符串到字节数组很多帮助,但不幸的是他们都没有为我工作。
我使用的方法是bytearray(),bytes(),str.encode()
。我使用了像编码 windows-1252,utf_16,utf_8,utf_16_le,utf_16_be,iso-8859-1
不幸的是他们没有给出正确的结果,因为我期望(即像我从Java getBytes()得到的字节数组)。我没有得到什么错误的事情,我在做什么。这是我如何在Python中尝试。
>>> bytearray('sr_shah','windows-1252')
bytearray(b'sr_shah')
>>> bytearray('sr_shah','utf_8')
bytearray(b'sr_shah')
>>> bytearray('sr_ahah','utf_16')
bytearray(b'sr_ahah')
>>> bytearray('sr_shah','utf_16_le')
bytearray(b'sr_shah')
>>> name = 'sr_shah'
>>> name.encode('windows-1252')
'sr_shah'
>>> name.encode('utf_8')
'sr_shah'
>>> name.encode('latin_1')
'sr_shah'
>>> name.encode('iso-8859-1')
'sr_shah'
>>> name.encode('utf-8')
'sr_shah'
>>> name.encode('utf-16')
'\xff\xfes\x00r\x00_\x00s\x00h\x00a\x00h\x00'
>>> name.encode('utf-16-le')
's\x00r\x00_\x00s\x00h\x00a\x00h\x00'
>>>
请帮助我得到正确的转换。
'[B @ 1ce59895'不是编码的字符串。它看起来像编码字符串的*地址*的表示。 –
问题在于你没有查看字节数组,只能看到字符串表示。 Java的'byte []。toString()'实现返回不是很有意义的''[B @“+ Integer.toHexString(hashCode())'表示,并且不清楚为什么要重现*那个输出。它看起来像python生成一个字符串表示形式,以与基于ASCII字符和编码的原始字符串相同的方式显示字节数组的内容。如果要比较数组的字节值,则必须将每个字节打印为数字(两种语言)。 – Holger
你确定'[B @ 1ce59895'不是指地址吗?我认为这意味着一个地址为0x1ce59895的字节数组。 – ErikR