Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string comparison (==) not working

Why the following String comparison is not working? I have the following code (I adapted it to make is simpler). I retrieve a player from the database and add it to a list of players. Then I loop on the list of player and try to find it, and even tho' the string is the same, the comparison return false..

def findPlayer2(self, protocol, playerId):
    cur = self.conn.cursor()
    cur.execute("SELECT playerId, playerName, rating FROM players WHERE playerId LIKE (%s)", [playerId])
    nbResult = cur.rowcount
    result = cur.fetchone()
    cur.close()

    if nbResult > 0:
        player = Player(protocol, str(result[0]), str(result[1]), result[2])
        self.players.append(player)

    for player in self.players:
        id1 = str(player.playerId)
        id2 = str(playerId)
        print type(id1)
        print type(id2)
        print "Comparing '%s' with '%s'" % (id1, id2)

# HERE IS THE COMPARISON

        if id1 == id2:
            print "Equal! Player found!"
            return player
        else:
            print "Not equal :("

Give the following result:

<type 'str'>
<type 'str'>
Comparing '11111111' with '11111111'
Not equal :(
like image 835
Henri Lapierre Avatar asked Jun 05 '13 14:06

Henri Lapierre


2 Answers

You seem to have a string processing error. PlayerId seems to be a C-String being stored in a unicode String.

Background: C uses a nullbyte (\x00) to mark the end of a string. Since this nullbyte is in your string it ends up in the string representation of the object.

You can take a look here, for some reference. But without more code I am not sure about the cause/fix.

Have you tried type(playerId)?

edit: I don't know what python implementation you are using, for cpython look here

Unfortunately I am not to firm in interfacing c and python, however you could try to use PyString_FromString to convert it on the c side to a python string or use some handcrafted function (eg split with regex at the first unescaped 0).

Some interfacing libs are listed in this awnser

like image 62
ted Avatar answered Oct 25 '22 21:10

ted


You can strip any non-printable characters like so

import string
player = ''.join(filter(lambda c: c in string.printable, player))
like image 44
Niklas R Avatar answered Oct 25 '22 22:10

Niklas R