python字符串比较(==)不工作

Hen*_*rre 7 python string comparison

为什么以下字符串比较不起作用?我有以下代码(我改编它使更简单).我从数据库中检索一个播放器并将其添加到播放器列表中.然后我循环播放器列表并尝试找到它,甚至'字符串是相同的,比较返回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 :("
Run Code Online (Sandbox Code Playgroud)

给出以下结果:

<type 'str'>
<type 'str'>
Comparing '11111111' with '11111111'
Not equal :(
Run Code Online (Sandbox Code Playgroud)

ted*_*ted 7

您似乎有一个字符串处理错误. PlayerId似乎是一个存储在unicode String中的C-String.

背景:C使用nullbyte(\x00)标记字符串的结尾.由于此nullbyby位于您的字符串中,因此它以对象的字符串表示形式结束.

您可以在这里查看,以供参考.但是没有更多的代码,我不确定原因/修复.

你试过type(playerId)吗?

编辑:我不知道你正在使用什么python实现,对于cpython来看这里

不幸的是我不会坚持接口c和python,但你可以尝试使用PyString_FromString它在c侧转换为python字符串或使用一些手工制作的功能(例如在第一个未转义的 0时用正则表达式拆分).

awnser中列出了一些接口库