【问题标题】:How to avoid the "ValueError: invalid \x escape" error in this special case?在这种特殊情况下如何避免“ValueError: invalid \x escape”错误?
【发布时间】:2012-08-30 14:57:36
【问题描述】:

显然,通配符 %x 未被识别为字节十六进制值,因此我收到错误“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()

【问题讨论】:

  • 你希望用这条线完成什么? \x<whatever> 只会在字符串文字中做一些有用的事情;你不能那样使用字符串格式。

标签: python syntax-error wildcard


【解决方案1】:

chr() 将为您提供 0 到 255 之间的值的字节串。

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

【讨论】:

    【解决方案2】:

    Ignacio 的答案是正确的,但也有原力的黑暗面:

    >>> 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')解决了您的问题,并使用 str.decode 方法将转义符转换为字符。 p>

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      相关资源
      最近更新 更多