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

2024-04-18 09:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下所示:

    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

但是,每次执行代码时,我都会遇到以下错误: 索引器错误:字符串索引超出范围

我试着排除故障以找出问题的原因,但我想不出来。你知道吗


Tags: theanstringifisvaluechecknow