我写这个是为了获取字符串 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)
最佳答案
当找到匹配时,您应该停止迭代:
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])
。
关于python - 字符串操作,for循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18687298/