【问题标题】:String Index out of range python?字符串索引超出范围python?
【发布时间】: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) &amp; set(string.digits)

标签: python string indexing range out


【解决方案1】:

当您重新输入密码时,由于密码无效,您不会将计数器 c 重置为零以重新从头开始检查过程。

# After this block
password= raw_input ()
numbercharacters=len(password) 
# Reset your counter to zero
c = 0
character=password[c]

您也可以简单地为您的字符检查数字与任一

while not character.isdigit():
# or 
while character not in '0123456789':

【讨论】:

    【解决方案2】:

    如果你想检查是否有数字,你可以这样做

    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." 
    

    如果你想重新输入密码直到它有一个数字

     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 ()
    

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 2016-08-11
      相关资源
      最近更新 更多