[英]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
After displaying the index value of the first string entered it is showing an error显示输入的第一个字符串的索引值后,显示错误
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
this is the error I get这是我得到的错误
As you are already looping through the string, you don't need the extra index:由于您已经在遍历字符串,因此不需要额外的索引:
while True:
stri=input("enter the strings : ")
if stri=="Exit" or stri=="exit":
break
for index, letter in enumerate(stri):
print(index, letter)
You can try something like this你可以试试这样的
while True:
stri=input("enter the strings : ")
if stri.lower() == 'exit':
break
for index, value in enumerate(stri):
print(index, " "+ value)
you don't need to keep the index use the pointer that you are using for writing the string charcters您不需要保留索引使用您用于编写字符串字符的指针
# 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)
Alternate solution替代解决方案
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
you need to init the index after each input您需要在每次输入后初始化索引
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.