我已经写了这个来获取字符串s1的第一个字符的索引,它已经出现在字符串s2中,但没有给出正确的答案,每次它抛出不同的错误答案时,谁都知道为什么?
s1 = input ('enter the s1 string: ')
s2 = input ('enter the s2 string: ')
for i in range (0, len(s1)):
if s1[i] in s2:
n= (s1.index(s1[i]))
else:
n= -1
print (n)
答案 0 :(得分:2)
发现匹配时应停止迭代:
s1 = input('enter the s1 string: ')
s2 = input('enter the s2 string: ')
n = -1
for i in range(0, len(s1)):
if s1[i] in s2:
n = i # Stop iteration when match character found.
break
print(n)
只需引用i
而不是s1.index(s1[i])
。