在Python 3.2中,我可以很容易地更改对象的类型。例如:
x=0
print(type (x))
x=bytes(0)
print(type (x))
它会给我这个:
<class 'int'>
<class 'bytes'>
但是,在Python 2.7中,似乎我不能使用同样的方法来做到这一点。如果我使用相同的代码,它会给我这个:
<type 'int'>
<type 'str'>
我该怎么将类型更改为字节类型?
你并未改变类型,而是将不同的值分配给变量。
你还触及到了Python 2.x和3.x之间的一个基本区别; 粗略地说,2.x的类型 unicode
已取代了str
类型,而后者已被重命名为bytes
。由于Python 2的较新版本已将bytes
作为str
的别名添加,因此代码可以正常工作。
换句话说,你的代码按照预期工作。
str
类型就是bytes
类型。 - Martijn Pieters我该怎么把类型改成字节类型?
在Python 2.7中,不存在'bytes'类型,因此你不能这样做。
根据Python 2.7文档(5.6序列类型): "共有七种序列类型:字符串、Unicode字符串、列表、元组、bytearray、缓冲区和xrange对象。"
根据Python 3.2文档(5.6序列类型): "共有六种序列类型:字符串、字节序列(bytes对象)、bytearray对象、列表、元组和range对象。"
>>> str is bytes
... True
-- 在Python2.x中有一种二进制序列类型,它就是str
! - anthony sottilebytes
只是str
的别名,所以一切都按预期工作。此外,您没有改变任何对象的类型 - 您只是将名称x
重新绑定到不同的对象上。也许不完全符合您的需求,但当我需要获取字节d8的十进制值(它是一个给定文件偏移量的字节)时,我这样做:
a = (data[-1:]) # the variable 'data' holds 60 bytes from a PE file, I needed the last byte
#so now a == '\xd8' , a string
b = str(a.encode('hex')) # which makes b == 'd8' , again a string
c = '0x' + b # c == '0xd8' , again a string
int_value = int(c,16) # giving me my desired offset in decimal: 216
#I hope this can help someone stuck in my situation
只是一个示例,强调将常规字符串转换为二进制字符串再转回来的过程:
sb = "a0" # just string with 2 characters representing a byte
ib = int(sb, 16) # integer value (160 decimal)
xsb = chr(ib) # a binary string (equals '\xa0')
现在倒序
back_sb = xsb.encode('hex')
back_sb == sb # returns True