Python string comparison (==) not working

Why doesn't the following string comparison work? I have the following code (I adapted it to make it easier). I extract the player from the database and add him to the list of players. Then I loop into the list of players and try to find it, and even though the string is the same, the comparison returns 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 :( 
+4
source share
2 answers

It seems you have a string processing error. PlayerId seems that the C-String is stored in a Unicode string.

Background: C uses a null byte ( \x00 ) to mark the end of a line. Since this null byte is on your string, it ends with a string representation of the object.

You can look here for some links. But without additional code, I'm not sure about the reason / fix.

Have you tried type(playerId) ?

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

Unfortunately, I'm not sure about the interaction of c and python, however you can try using PyString_FromString to convert it in c side to the python string or use some handcrafted function (e.g. split with regex on the first unselected 0).

Some front-end libraries are listed in this awnser.

+5
source

You can strip any non-printable characters this way

 import string player = ''.join(filter(lambda c: c in string.printable, player)) 
+1
source

Source: https://habr.com/ru/post/1484660/


All Articles