[英]String Index out of range python?
I am making a security login program in python, and I keep getting this error message: IndexError: string index out of range.
我正在用python创建一个安全登录程序,并且不断收到此错误消息:
IndexError: string index out of range.
The error is for the line character=password[c]
. 错误是针对line
character=password[c]
。 I am at the part where it checks if the password that the user enters has a number. 我正在检查用户输入的密码是否有数字。 If it does not have a number, the password is invalid.
如果没有数字,则密码无效。 How do I fix this?
我该如何解决?
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
is the variable for the counter. c
是计数器的变量。
When you get fresh input for the password, due to it being invalid, you don't reset your counter c
to zero to start the checking process from scratch again. 当您获得新的密码输入时(由于无效),您无需将计数器
c
重置为零即可再次从头开始检查过程。
# After this block
password= raw_input ()
numbercharacters=len(password)
# Reset your counter to zero
c = 0
character=password[c]
You can also simply for your character check for digits with either 您也可以简单地使用以下任一方法为字符检查数字
while not character.isdigit():
# or
while character not in '0123456789':
If you want to check if there is a number you can just do 如果要检查是否有电话号码,您可以做
password= raw_input ()
if not any(character.isdigit() for character in password):
print "This password is not valid, it does not contain a number. Please create another."
If you want to re-ask for a password until it has a number 如果您想重新询问密码直到输入密码
password= raw_input ()
if not any(character.isdigit() for character in password):
while not any(character.isdigit() for character in password):
print "This password is not valid, it does not contain a number. Please create another."
password= raw_input ()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.