如何查看Python3 <class'bytes'=“”>对象的字节?</class>

时间:2013-06-13 07:09:02

标签: python python-3.x type-conversion bytestring

考虑到the bytes type is not necessarily a string,如何看到bytes对象的实际字节(1和0,或者八进制/十六进制表示)?尝试print()pprint()这样的对象会导致打印对象的字符串表示(假设某些编码,可能是ASCII或UTF-8),前面是b字符,表示数据类型实际上是字节:

$ python3
Python 3.2.3 (default, Oct 19 2012, 19:53:16) 
>>> from pprint import pprint
>>> s = 'hi'
>>> print(str(type(s)))
<class 'str'>
>>> se = s.encode('utf-8')
>>> print(str(type(se)))
<class 'bytes'>
>>> print(se)
b'hi'
>>> pprint(se)
b'hi'
>>>

请注意,我特指Python 3。谢谢!

4 个答案:

答案 0 :(得分:3)

使用binocthex并使用括号表示法访问该字节:

>>> print(hex(se[0]))
0x68
>>> print(hex(se[1]))
0x69

显然一个周期会更好:

for a_byte in se:
    print (bin(a_byte))

答案 1 :(得分:2)

使用Python string formatting显示字节的十六进制值:

>>> se = b'hi'
>>> ["{0:0>2X}".format(b) for b in se]
['68', '69']

答案 2 :(得分:0)

print(se.decode(“ utf8”))

答案 3 :(得分:-1)

>>> s = b'hi'
>>> s
b'hi'
>>> print(s)
b'hi'
>>> for i in s:
    print(i)


104
105
>>> y = 'hi'
>>> for i in y:
    print(i)


h
i
>>>