python - If statement 'not working' despite conditions being true -
currently going through bin file full of hex data process, match i'm using try , find group of 3 hex bytes in file aren't working correctly. values identical not printing string i've got set confirm match, @ present i'm trying match first 3 bytes know works etc. code follows:
match1 = "\\x00\\n\\x00" print ("match1 ="+match1) if bytedata == match1: print ("byte string 030791 found!") elif bytedata == match1: print ("byte string 050791 found!") exit()
the value of bytedata '\x00\n\x00' script ignores , moves exit statement. file being opened follows :
file = open('file.bin', 'rb') while true: byte = file.read(3)
when printing value of byte reports "\x00\n\x00" have ideas why match isn't working properly?
match1
not contain 3 bytes. contains 10:
>>> match1 = "\\x00\\n\\x00" >>> len(match1) 10
you escaped escape sequences, \\x00
four bytes, \
backslash, letter x
followed 2 0
digits.
remove backslash escapes:
match1 = "\x00\n\x00"
don't try print directly; terminals won't make nulls visible, newline. use repr()
function produce debug output looks python string can reproduce value in code or interactive interpreter:
print ("match1 =", repr(match1))
this how interactive interpreter shows expression results (unless produced none
):
>>> match1 = "\x00\n\x00" >>> len(match1) 3 >>> match1 '\x00\n\x00' >>> print("match1 =", repr(match1)) match1 = '\x00\n\x00'
next, if using python 3, you'll still won't have match because opened file in binary mode , getting bytes
objects, match1
variable str
text sequence. if want 2 types match you'll either have convert (encode text or decode bytes), or make match1
bytes
object start with:
match1 = b'\x00\n\x00'
the b
prefix makes bytes
literal.
Comments
Post a Comment