2012-08-30 76 views
2

顯然通配符%x不被識別爲字節十六進制值,所以我得到錯誤「ValueError:invalid \ x escape」。如何避免在這種特殊情況下出現「ValueError:invalid x escape」錯誤?

如何避免這種情況?我不熟悉python。

for i in xrange(0,length): 

    if i % 2 == 0: 

    tempArray.append(unpack("B",payload_raw[x])[0]^key) 
    x += 1 

    else: 

    randomByte = random.randint(65,90) 
    tempArray.append(randomByte) 

    for i in range(0,len(tempArray)): 

     tempArray[i]="\x%x"%tempArray[i] 

    for i in range(0,len(tempArray),15): 

     outArray.append("\n'"+"".join(tempArray[i:i+15])+"'") 
     outArray = "".join(outArray) 
     devide = "i % 2;" 
     open_structure = open(structure).read() 
     code = open_structure % (junkA,outArray,junkB,key,length,devide) 
     b.write(code) 
     b.flush() 
+0

你希望用這條線完成什麼? '\ x​​'只會在字符串文字中做一些有用的事情;你不能以這種方式使用字符串格式。 – geoffspear

回答

5

chr()會給你的字節串爲0和255之間的值

>>> chr(0xd3) 
'\xd3' 
2

伊格納西奧的答案是正確的,但也有原力的黑暗面:

>>> your_string = r'\x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\x64\x21' 
>>> your_string.decode('string-escape') 
'Hello, World!' 

所以你可能已經使用原始文字(r'\ x'而不是'\ x')修復了您的問題,並將轉義轉換爲charac與str.decode方法。

相關問題