我正在尝试显示使用输入函数获得的字符串的索引值

I am trying to display the index value of strings which I have obtained using the input function

index=0

while True:
    stri=input("enter the strings : ")
    if stri=="Exit" or stri=="exit":
        break
    for indexes in stri:
        letter=stri[index]
        print(index, letter)
        index=index+1

显示输入的第一个字符串的索引值后显示错误

    enter the strings : abcdfg
0 a
1 b
2 c
3 d
4 f
5 g
enter the strings : qwerty
Traceback (most recent call last):
  File "len.py", line 10, in <module>
    letter=stri[index]
IndexError: string index out of range

这是我得到的错误

您不需要使用您用于编写字符串字符的指针来保留索引

# index=0

while True:
    stri=input("enter the strings : ")
    if stri=="Exit" or stri=="exit":# you can directly use lower()
        break
    for indexes in range(len(stri)):
        letter=stri[indexes]
        print(indexes+1, letter)

替代解决方案

while True:
    stri=input("enter the strings : ")
    if stri=="Exit" or stri=="exit":# you can directly use lower()
        break
    index=0
    for indexes in range(len(stri)):
        letter=stri[index]
        print(index+1, letter)
        index+=1

每次输入后需要初始化索引



while True:
    index=0
    stri=input("enter the strings : ")
    if stri=="Exit" or stri=="exit":
        break
    for indexes in stri:
        letter=stri[index]
        print(index, letter)
        index=index+1

因为您已经在遍历字符串,所以不需要额外的索引:

while True:
    stri=input("enter the strings : ")
    if stri=="Exit" or stri=="exit":
        break
    for index, letter in enumerate(stri):
        print(index, letter)

你可以试试这样的

while True:
    stri=input("enter the strings : ")
    if stri.lower() == 'exit':
        break
    for index, value in enumerate(stri):
        print(index, " "+ value)