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

标签 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)

最佳答案

当找到匹配时,您应该停止迭代:

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/

相关文章:

python - SCU 如何使用 C-GET 从 Dicom 服务器接收 dcm 图像?

python - IPython 笔记本内核在运行 Kmeans 时死机

python - 如何使用 Python 3 按字母数字顺序对 os.walk(path) 进行排序,并将重复项放在原始文件之后?

python - 使用 LXML 将 XML 写入文件

python-3.x - 如何将 Kafka 消费者连接到 Django 应用程序?我应该为消费者或新进程或新的 docker 容器使用新线程吗?

python - 导入错误 : No module named newspaper

python - 组织 Python 类(class)的最佳方式是什么?

python - 根据列表对 Pandas 数据框进行排序

python - ValueError : Length of passed values is 7, 索引意味着 0

python-3.x - 假redis中没有名为 'lupa'的模块