Hi all I have this part of code:
for line in response.body.split("\n"):
if line != "":
opg = int(line.split(" ")[2])
opc = int(line.split(" ")[3])
value = int(line.split(" ")[5])
if opg==160 & opc==129:
ret['success'] = "valore: %s" % (value)
self.write(tornado.escape.json_encode(ret))
I have a series if line of type
1362581670 2459546910990453036 156 0 30 0
I want to take only the line where the third and fourth element are respectively 160 and 129. This code doesn't work. Do I have to do some casting? I think opg==160 is working to campare int with int...
&
is a bitwise operation. You probably wantand
. With integers, you might not think that it would make a differenceHowever, note that
&
andand
have different priorities.Basically,
&
binds tighter than==
, soa == b & c == d
is parsed asa == ( b & c) == d
rather than(a == b) & (c == d)
like you wanted.As pointed out by Hoopdady, you also aren't splitting your string correctly.
line.split()
orline.split(None)
will split on consecutive runs of whitespace.Just use
line.split()
instead ofline.split(" ")
. That way it handles any type of whitespace. If those aren't just spaces, you'll get some weird results, which may be what's happening.You got confused with the operators;
and
is the correct boolean test,&
is a binary bitwise operator instead:As a numeric operator, the
&
operator has a higher precedence than comparison operators, while the boolean operators have a lower precedence. The expressionopg == 160 & opc == 129
is thus interpreted asopg == (160 & opc) == 129
instead, which is probably not what you wanted.You can simplify your code somewhat: