为什么Python 3.5返回TypeError而不是Python 2.7

时间:2016-09-11 15:31:48

标签: python python-2.7 python-3.x

我在Python 2.7中有一段代码:

def reversetomd5(knownhash):
  clean="" 
  for i in [1,2,3,4,5,7,8,9,10,11,13,14,15,16,18,19,20,21,22,24,25,26,27,28]:
    clean+=knownhash[i]
 b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
 block=[]
 for i in xrange(2,24,3):
   p1 = b64.index(clean[i-2])
   p2 = b64.index(clean[i-1])
   p3 = b64.index(clean[i])
   block.append(p1 << 12 | p2 << 6 | p3)
 md5hash=""
 for i in block:
   n1 = i >> 8
   n2 = i & 0xff
   md5hash+=chr(n1)+chr(n2)
 return binascii.hexlify(md5hash)

我正在努力让它在Python 3.5中工作我将xrangerange交换,但是底部的字符移位不再起作用并返回TypeError: a bytes-like object is required, not 'str'。我无法弄清楚Python 3中的变化导致了什么。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

让它正常工作。已替换chr()以返回该字符的byte等效项。必须将md5hash初始化更改为空byte变量而不是string。然后只是.decode()它在最后返回一个很好的字符串。

def reversetomd5(knownhash):
  clean="" 
  for i in [1,2,3,4,5,7,8,9,10,11,13,14,15,16,18,19,20,21,22,24,25,26,27,28]:
    clean+=knownhash[i]
 b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
 block=[]
 for i in range(2,24,3):
   p1 = b64.index(clean[i-2])
   p2 = b64.index(clean[i-1])
   p3 = b64.index(clean[i])
   block.append(p1 << 12 | p2 << 6 | p3)
 md5hash=b''
 for i in block:
   n1 = i >> 8
   n2 = i & 0xff
   md5hash+=bytes[(n1)]+bytes[(n2)]
 return binascii.hexlify(md5hash).decode()