python字符串比较(==)不起作用

为什么以下字符串比较不起作用?我有以下代码(我对其进行了修改以使其更简单)。我从数据库中检索一个播放器,并将其添加到播放器列表中。然后,我在播放器列表上循环并尝试找到它,即使字符串相同,比较也返回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 :("

给出以下结果:


<type 'str'>

<type 'str'>

Comparing '11111111' with '11111111'

Not equal :(


森林海
浏览 346回答 3
3回答

明月笑刀无情

您似乎有一个字符串处理错误。 PlayerId似乎是一个存储在Unicode字符串中的C字符串。背景:C使用空字节(\x00)标记字符串的结尾。由于此nullbyte位于您的字符串中,因此最终以该对象的字符串表示形式结束。您可以在这里看看,以供参考。但是如果没有更多代码,我不确定原因/解决方法。你试过了type(playerId)吗?编辑:我不知道您正在使用什么python实现,对于cpython看看这里不幸的是,我并不是很确定c和python的接口,但是您可以尝试使用PyString_FromStringc端将其转换为python字符串,或者使用一些手工函数(例如,在第一个未转义的0处使用regex进行拆分)。此探视器中列出了一些接口库
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python