Problem when comparing characters of differnt strings, IndexError: string index out of range

Problem when comparing characters of differnt strings, IndexError: string index out of range

我正在尝试比较两个字符串,比较每个字符,以便相同位置的共同字符数越多,终端将 return.

代码如下:

resultado=input('Resultado correcto: ')
apuesta=input('Apuestas: ')

puntos=0
contador=0
while contador <= len(resultado):
    if resultado[contador] == apuesta[contador]:
        puntos = puntos +1
    else:
        puntos = puntos
    contador+=1
print(puntos)

但是当我 运行 程序时,它给了我下一个错误:

if resultado[contador] == apuesta[contador]:
IndexError: string index out of range

不知道怎么回事,估计跟计数器和字符数有关。值得注意的是 两个输入具有相同数量的字符,例如你好你好.

索引contador应该小于你的字符串的长度,你可以使用:

while contador < len(resultado):

这是因为索引从 0

开始

要比较字符串中相同位置的字符并获得相同字符的总数,您还可以使用内置函数 sum 和生成器表达式:

puntos = sum(a == b for a, b in zip(resultado, apuesta))