简体   繁体   English

Python错误:IndexError:字符串索引超出范围

[英]Python Error: IndexError: string index out of range

My code looks like this: 我的代码如下所示:

    value = input("Please enter your 8-digit code: ")
if len(value) < 8 or len(value) > 8:
    print("Double check to make sure that was 8-digits")
    restart()

#Checking if the string is all numeric
while not value.isdigit():
    value = input("Please enter as numeric ") # eg 12345678

if value.isdigit():
    #removing the 8th digit and storing it as "check_digit"    
    check_digit = value[7]                  
    #be sure to check whether or not there is 8 numbers 
    newvalue = value.replace(value[7], "")  #1234567  8

#reversing the string https://stackoverflow.com/questions/931092/reverse-a-string-in-python
newvalue = newvalue[::-1] #7654321  8

#multiplying the 1st, 3rd, 5th and 7th digits by 2
value1 = newvalue[0]    
value1 = int(value1) * 2 #value1 is now an int
if value1 > 9:
    value1 = value1 - 9

value2 = newvalue[2]
value2 = int(value2) * 2 #value2 is now an int
if value2 > 9:
    value2 = value2 - 9

value3 = newvalue[4]
value3 = int(value3) * 2 #value3 is now an int
if value3 > 9:
    value3 = value3 - 9

value4 = newvalue[6]
value4 = int(value4) * 2 #value4 is now an int
if value4 > 9:
    value4 = value4 - 9

However Each time I execute the code I am greeted by this error: IndexError: string index out of range 但是,每次执行代码时,都会遇到以下错误:IndexError:字符串索引超出范围

I have tried to troubleshoot to find the cause of the problem but I can't figure it out. 我试图进行故障排除以找到问题的原因,但我无法解决。

newvalue = value.replace(value[7], "")  #1234567  8

This code removes ALL the digits that equal value[7]. 此代码删除所有等于value [7]的数字。 Try this code instead: 请尝试以下代码:

newvalue = value[:7]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM