为什么IF条件总是被评估为True

2024-05-29 01:43:22 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么每次都将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次。为什么呢


Tags: 代码intrue密码forlenifrange
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 ''

查看所有情况也会很有帮助-很多情况下,如果条件未通过:

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'

IF条件并非始终被计算为True。这是因为在某些循环中,i >= j。当这种情况发生时,s1[i:j]将返回一个空字符串作为“”

if condition中,检查s1[i:j]是否包含在s2中。根据上述场景,您将检查s1[i:j](一个空字符串)是否包含在s2

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

if '' in s2: # this is always true

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

只要有i >= j,就会得到s1[i:j]的空字符串。当检查另一个字符串时,空字符串总是返回True,因此您的打印语句

相反,您应该将j作为i + 1开始:

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')

没有输出


Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

Docs source

相关问题 更多 >

    热门问题