python检查列表中是否有空字符串

时间:2017-05-10 10:21:05

标签: python string list

不久前,我遇到if '' in lst的奇怪事情。 下面的代码给出了输出:

1 - yes
2 - no
3 - yes

你能告诉我为什么1yes

########################################
if '' in ('a'):
    print('1 - yes')
else:
    print('1 - no')


########################################
if '' in ('a', 'b', 'c'):
    print('2 - yes')
else:
    print('2 - no')


########################################
if '' in (''):
    print('3 - yes')
else:
    print('3 - no')

6 个答案:

答案 0 :(得分:4)

>>> print(type(('a')))
<class 'str'>

所以你可以意识到发生了什么。 ('a')会自动转换为字符串,因此if '' in ('a')等于if '' in 'a',每个字符串中都会出现一个空字符串。

答案 1 :(得分:4)

if '' in ('a'):
    print('1 - yes')
else:
    print('1 - no')

您正在测试字符串a中是否包含空字符串,因为('a')不是元组,它只是字符串'a'。空字符串始终被视为包含在任何其他非空字符串中。

如果要创建仅包含字符串('a')的元组,则应将('a',)更改为'a'

答案 2 :(得分:4)

('a')是一个字符串,简化为'a',所有字符串都包含空字符串。如果你把它作为一个元组,那么你就得到False,就像'' in ('a',)一样。

答案 3 :(得分:3)

你应该这样做 -

if '' in ('a',):
   print('1 - yes')
else:
   print('1 - no')

('a')只是字符串'a',其中('a',)是元组

答案 4 :(得分:2)

Empty strings始终被视为任何其他substring的{​​{1}}。

string

这意味着>>> 'a'.find('') 0 中存在'',因此'a''' in ('a')

答案 5 :(得分:1)

您可以认为:

'a' = '' + 'a' + ''

在第二个例子中 - &#39;&#39;不是列表的元素。元素是&#39; a&#39;&#39; b&#39;和&#39; c&#39;。

相关问题