Question

I'm trying to escape items in a list by checking them against another list of items. I can filter the list:

@staticmethod
def escapeFrameData(frameData):
  toEscape = [0x7e, 0x7d, 0x11, 0x13]

  genExpr = (x for x in frameData if x in toEscape)
  for x in genExpr:
    print x

Now I'd like to put the escape character in front of each item found. Something like this:

genExpr = (x for i, x in frameData if x in enumerate(toEscape))

for x in genExpr:
  frameData.insert(i-1, 0x7d)
return frameData

Needed behaviour:

frameData = [0x02, 0x7e, 0x04]
escaped = class.escapeFrameData(frameData)
escaped is now: [0x02, 0x7d, 0x7e, 0x04]

How would the generator expression have to be written to accomplish this? Is there a better way to get the desired result?

Was it helpful?

Solution

This looks like a really slow way to go about solving this problem. A better approach, assuming these are bytes (it looks like they are) would be to use byte strings and the re module. For instance, you might write

re.sub(r'[\x7e\x7d\x11\x13]', b'\x7d\\1', frameData)

OTHER TIPS

Use a generator function instead:

@staticmethod
def escapeFrameData(frameData):
    toEscape = {0x7e, 0x7d, 0x11, 0x13}
    for x in frameData:
        if x in toEscape:
            yield 0x7d
        yield x

I replaced your list of to-escape values with a set for faster lookups.

You'd call list() on the function:

escaped = list(class.escapeFrameData(frameData))

or just loop over the generator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top