簡體   English   中英

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

[英]python check if empty string is in list

不久前我第一次在if '' in lst里遇到奇怪的事情。 下面的代碼給了我輸出:

1 - yes
2 - no
3 - yes

你能告訴我為什么1 yes嗎?

########################################
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')
>>> print(type(('a')))
<class 'str'>

這樣您就可以知道發生了什么。 ('a')自動轉換為字符串,因此if '' in ('a') if '' in 'a'等於if '' in 'a' ,並且每個字符串中都有一個空字符串。

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

您正在測試字符串a是否包含空字符串,因為('a')不是元組,它只是字符串'a' 空字符串始終被視為包含在任何其他非空字符串中。

如果要創建僅包含字符串'a'的元組,則應將('a')更改為('a',)

('a')是一個字符串,簡化為'a' ,並且所有字符串都包含一個空字符串。 如果將其設為元組,則將得到False ,如'' in ('a',)

您應該這樣做-

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

('a')只是字符串'a'其中('a',)是一個元組

Empty strings始終被視為任何其他stringsubstring string

>>> 'a'.find('')
0

這意味着''存在於'a' ,因此'' in ('a')True

您可以假設:

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

在第二個示例中-''不是列表的元素。 元素是“ a”,“ b”和“ c”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM