Issue
I have a hex string and I need to compare the string by checking if '\' is in value and then do and do encode operation
value='\x1a\x01'
(Pdb) value.encode("hex")
'1a01'
However when i check like this its returning false
(Pdb) '\\' in value
False
Solution
You can encode the x-escaped sequences using re.sub
.
First of all, define a regular expression that will capture these sequences.
import re
pattern = re.compile(r'\\x[0-9a-fA-f]{2}') # matches \x and two-digit hex value
Note that \x
needs to be escaped so that the re compiler doesn't reject it as a bogus regex escape sequence.
Now define a function that will encode the matched sequences.
def enc(match):
return match.group(0).decode('string-escape').encode('hex')
When encoding, we need to decode from 'string-escape' first because we need to escape the input string so that the \x..
sequences get matched.
Now perform the substitution on a string-escaped version of the input string, remembering to decode the output afterwards (otherwise sequences like \n
will be escaped):
s = 'abc\x1a\x01def'
escaped = re.sub(pattern, enc, s.encode('string-escape'))
result = escaped.decode('string-escape')
print result
abc1a01def
Answered By - snakecharmerb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.