【发布时间】:2016-02-10 13:45:24
【问题描述】:
我正在用 python 制作一个安全登录程序,但我不断收到此错误消息:IndexError: string index out of range.
错误是针对character=password[c] 行。我在检查用户输入的密码是否有数字的部分。如果没有数字,则密码无效。我该如何解决这个问题?
while c<numbercharacters:
character=password[c]
c=c+1
while character!="1" and character!="2" and character!="3" and character!="4" and character!="5" and character!="6" and character!="7" and character!="8" and character!="9" and character!=0: #checking if password has a number
print "This password is not valid, it does not contain a number. Please create another."
password= raw_input ()
numbercharacters=len(password)
character=password[c]
c 是计数器的变量。
【问题讨论】:
-
修复缩进,以便我们确切知道您在说什么。
-
并重新排序代码,我认为第一个 while 应该放在 numbercharacters=len(password) 之后
-
c与外循环保持不变,因此如果用户重新输入较短的密码,c 将超出范围。 -
其中一个与其他的不同:
character != 0 -
not any(character.isdigit() for character in password)或者not set(password) & set(string.digits)。
标签: python string indexing range out