为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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

3 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

您似乎有一个字符串处理错误。 PlayerId似乎是一个存储在Unicode字符串中的C字符串。


背景:C使用空字节(\x00)标记字符串的结尾。由于此nullbyte位于您的字符串中,因此最终以该对象的字符串表示形式结束。


您可以在这里看看,以供参考。但是如果没有更多代码,我不确定原因/解决方法。


你试过了type(playerId)吗?


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


不幸的是,我并不是很确定c和python的接口,但是您可以尝试使用PyString_FromStringc端将其转换为python字符串,或者使用一些手工函数(例如,在第一个未转义的0处使用regex进行拆分)。


此探视器中列出了一些接口库


查看完整回答
反对 回复 2021-03-30
  • 3 回答
  • 0 关注
  • 345 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号