我的代码如下所示:
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
然而,每次执行代码时,我都会遇到此错误: IndexError:字符串索引超出范围
我尝试排查问题但找不到问题的原因,但我无法弄明白。
答案 0 :(得分:0)
newvalue = value.replace(value[7], "") #1234567 8
此代码删除所有等于值[7]的数字。请尝试使用此代码:
newvalue = value[:7]