基于Python 2.7的Tweepy代码条件判断不生效问题求助
问题排查:Tweepy推文定制判断不生效
问题场景
使用Python 2.7 + Mystic Python开发,通过Tweepy实现BBS用户登录时自动发送推文。添加用户handle判断逻辑后,当用户handle为「Talon」时,未触发定制化推文,反而执行了else分支,实际推送内容为「TALON has just logged into the trans-dimensional portal, and is available to converse!」。
完整代码
import tweepy import sys from mystic_bbs import * consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) thisuser = getuser(0); # read the currently logged in user into thisuser writeln("|11 STANDBY Updating Status within Profundum!"); api = tweepy.API(auth) if thisuser["handle"] == "Talon": tweet_text = thisuser["handle"] + ", the Eternal Leader of Civitas Nihilium, has just logged into the trans-dimensional portal, and is available to converse!" else: tweet_text = thisuser["handle"] + " has just logged into the trans-dimensional portal, and is available to converse!" api.update_status(status=tweet_text)
问题原因
Python字符串比较是大小写敏感的。从实际推送的「TALON」可以看出,thisuser["handle"]返回的是全大写的字符串,而判断条件中写的是首字母大写的「Talon」,两者无法匹配,因此执行了else分支。
解决方法
方案1:统一大小写后比较(推荐)
将两边字符串统一转为小写或大写,避免大小写差异导致的匹配失败:
# 转为小写比较 if thisuser["handle"].lower() == "talon":
或者
# 转为大写比较 if thisuser["handle"].upper() == "TALON":
方案2:直接匹配实际大写值
如果确认thisuser["handle"]始终返回全大写字符串,可直接修改判断条件:
if thisuser["handle"] == "TALON":
调试建议
可以在判断前添加打印语句,确认thisuser["handle"]的实际内容:
print("当前用户handle:%r" % thisuser["handle"])
通过repr()能清晰看到字符串的真实状态(比如是否包含空格、特殊字符或大小写差异)。
内容的提问来源于stack exchange,提问作者James Bradley
相关产品推荐
相关产品推荐

