Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python bitand (&) vs and

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 of line of type

1362581670        2459546910990453036    156     0     30      0

I want to take only the line where the third and fourth element is respectively 160 and 129. This code doesn't work. Do I have to do some casting? I think opg==160 is working to compare int with int...

like image 212
sharkbait Avatar asked Dec 27 '22 08:12

sharkbait


2 Answers

You got confused with the operators; and is the correct boolean test, & is a binary bitwise operator instead:

if opg == 160 and opc == 129:

As a numeric operator, the & operator has a higher precedence than comparison operators, while the boolean operators have a lower precedence. The expression opg == 160 & opc == 129 is thus interpreted as opg == (160 & opc) == 129 instead, which is probably not what you wanted.

You can simplify your code somewhat:

for line in response.body.splitlines():
    if line:
        line = map(int, line.split())
        opg, opc, value = line[2], line[3], line[5]
        if opg == 160 and opc == 129:
            ret['success'] = "valore: %s" % (value)
            self.write(tornado.escape.json_encode(ret))
like image 193
Martijn Pieters Avatar answered Dec 28 '22 21:12

Martijn Pieters


Just use line.split() instead of line.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.

like image 45
Hoopdady Avatar answered Dec 28 '22 22:12

Hoopdady