Python ' in '关键字给出假阳性



我一直在使用in关键字来检查字符是否在元组中可用然后得到一个奇怪的结果。如果有人能解释下面最后一个结果,我会很感激。提前谢谢你。

>>> '' in ('n','p','')
True
>>> '' in ('n','p')
False
>>> '' in ('n')
True

编辑

正如Anthony的评论中所解释的那样,我似乎把('n')(只是一个括号中的字符串)误认为是元组。使用('n',)效果如预期。

单条目元组,记住逗号:

thistuple = ("n",)
print(type(thistuple))

输出:

<class 'tuple'>

但:

#NOT a tuple
thistuple = ("n")
print(type(thistuple))

输出:

<class 'str'>

最新更新