字符串操作,for循环不起作用

时间:2013-09-08 18:41:07

标签: python python-3.x

我已经写了这个来获取字符串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)

1 个答案:

答案 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])

相关问题