Python 3.x 为什么在python中使用空白输入print if语句

Python 3.x 为什么在python中使用空白输入print if语句,python-3.x,if-statement,Python 3.x,If Statement,我只想说,如果我给s1一些输入,而不给s2任何输入,然后按enter键,这个代码的输出打印“found” 这是错误的,因为空格不在字符串s1中,所以为什么会发生这种情况?如何更正它?每个字符串都包含空字符串,因此“任何东西”中的''总是真的每个字符串都包含空字符串 s1 = input("enter 1st string: ") s2 = input("enter 2nd string: ") if s2 in s1: print("found") else: print("n

我只想说,如果我给s1一些输入,而不给s2任何输入,然后按enter键,这个代码的输出打印“found”
这是错误的,因为空格不在字符串s1中,所以为什么会发生这种情况?如何更正它?

每个字符串都包含空字符串,因此“任何东西”中的
''总是
真的
每个字符串都包含空字符串

s1 = input("enter 1st string: ")
s2 = input("enter 2nd string: ")

if s2 in s1:
    print("found")
else:
    print("not found")
如您所见,在每个字母之间以及字符串前后,都有“空字符串”

在您的示例中,您可以确保输入非空字符串,如下所示:

i = 'anything'.count('')

print(i)
# 9
另请注意:

while(True):
    s1 = input("enter 1st string: ")
    if s1 != '':
        break

while(True):
    s2 = input("enter 2nd string: ")
    if s2 != '':
        break

if s2 in s1:
    print("found")
else:
    print("not found")
添加更多空字符串没有任何效果

s  = '' + 'a' + '' + 'n'+ '' + 'y' + '' + 't' + '' + 'h' + '' + 'i' + '' + 'n' + '' + 'g' + ''

print(s == 'anything')
# True
print(s.count('')
# 9
s += ''
print(s.count('')
# 9