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
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?
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)