为什么IF条件始终被评估为True

4
为什么if语句每次都被评估为True,即使我故意给我的代码提供了有偏见的输入。以下是我的代码:
s1 = 'efgh'
s2 = 'abcd'

for i in range(0, len(s1)):
    for j in range(1, len(s1)+1):
        if s1[i:j] in s2:
            print('YES')

它会打印YES,6次。为什么呢?


你想要的输出是什么? - Mojtaba Kamyabi
1
你可以尝试在循环中添加print(s1[i:j], s2)以查看它们的值。你正在检查s1切片的空字符串。 - ggorlen
1
一个空字符串是每个字符串的子字符串。 - Błotosmętek
3个回答

5
无论何时当 i >= j 时,你将会得到一个空字符串s1[i:j]。当检查另一个字符串中的in时,空字符串总是返回True,这就是你的打印语句。
相反,你应该以i+1 开始j
s1 = 'efgh'
s2 = 'abcd'

for i in range(0,len(s1)):
    for j in range(i + 1,len(s1)+1):
        if s1[i:j] in s2:
            print('YES')

没有任何输出。


空字符串总是被认为是另一个字符串的子字符串,因此在“abc”中的“”将返回True。

文档来源


3

由于某些组合会生成空字符串:

s1 = 'efgh'
s2 = 'abcd'

for i in range(0, len(s1)):
    for j in range(1, len(s1) + 1):
        if s1[i:j] in s2:
            print('YES', i, j, repr(s1[i:j]))

输出:

YES 1 1 ''
YES 2 1 ''
YES 2 2 ''
YES 3 1 ''
YES 3 2 ''
YES 3 3 ''

如果能够查看所有的情况,这对于解决问题也会很有帮助——因为 if 条件不一定总是成立的。

s1 = 'efgh'
s2 = 'abcd'

for i in range(0, len(s1)):
    for j in range(1, len(s1) + 1):
        print(s1[i:j] in s2, i, j, repr(s1[i:j]))

输出:

False 0 1 'e'
False 0 2 'ef'
False 0 3 'efg'
False 0 4 'efgh'
True 1 1 ''
False 1 2 'f'
False 1 3 'fg'
False 1 4 'fgh'
True 2 1 ''
True 2 2 ''
False 2 3 'g'
False 2 4 'gh'
True 3 1 ''
True 3 2 ''
True 3 3 ''
False 3 4 'h'

0

IF条件并不总是被评估为True。这是因为在一些循环中,i >= j。当发生这种情况时,s1[i:j]将返回一个空字符串''。

在您的if条件中,您检查s1[i:j]是否包含在s2中。根据上述情况,您将检查s1[i:j](即一个空字符串)是否包含在s2中。

默认情况下,每个字符串都有一个空字符串。这就像检查以下内容:

if '' in s2: # this is always true

根据你的代码,s1 中不包含任何也包含在 s2 中的字符。因此,这只会在 i >= j 的情况下发生。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接