蛮力python“超出范围错误”

2024-09-27 21:26:33 发布

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

我对Python还不熟悉。我有一个简单的暴力程序,但不能让它工作。代码生成了一个string index out of range错误,但是我发现字符串与范围一致。你知道吗

我键入aa作为密码

import string
alphabet = string.ascii_lowercase[:]
#Get the password
passd = str.lower(input("Please enter you password: "))
rpass = []
counter = 0
i = 0
j = 0
while counter <= len(passd): 
   #Check if the letters match
   if alphabet[i] == passd[j]: 
    rpass.append(passd[j])
    i += 1
    j += 1
    counter += 1
  else:
    i += 1

print(rpass)

Tags: ofthe程序stringindexifcounterrange
1条回答
网友
1楼 · 发布于 2024-09-27 21:26:33

i需要设置为0,以便在找到匹配项时从字母表的开头重新开始,并且您的while应该只检查counter是否为< len(passd)

while counter < len(passd): 
   #Check if the letters match
   if alphabet[i] == passd[j]: 
    rpass.append(passd[j])
    i = 0
    j += 1
    counter += 1
   else:
    i += 1

(请注意,如果您的字母不是字母表的一部分,例如空格键,则此操作似乎仍然失败。)

请注意,您的输入可以简化为:

passd = input("Please enter your password: ").lower()

相关问题 更多 >

    热门问题