【问题标题】:How do I check if a letter is not in a word?如何检查一个字母是否不在一个单词中?
【发布时间】:2017-02-26 11:15:32
【问题描述】:
while True:
    profilePassword = input("Password: ")
    if profilePassword == "":
        print("Your password can't be blank!")
        continue
    else:
        pass
    for n in profilePassword:
        if n == " ":
            print("Your password can't contain spaces!")
            break
        elif n not in "1234567890":
            print("Your password has to contain at least one number!")
            break
        elif n not in "abcdefghijklmnopqrstuvwxyz":
            print("Your password has to contain at least one lowercase letter!")
            break
        elif n not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            print("Your password has to contain at least one uppercase letter!")
            break
        else:
            continue

所以我正在尝试创建一个程序来检查您的密码是否正确。出于某种原因,“不在”表现不佳。例如,如果我写 asd123,它会说密码必须包含至少一个数字,它有。 为什么会这样,我该如何解决?

【问题讨论】:

  • 我会退后一步,通过您正在尝试的逻辑流程与自己交谈。您应该注意到的第一件事是,除非profilePassword 中的第一个字符是数字,否则您的逻辑流程永远不会超过elif n not in "1234567890"。对于其余的 elif 语句,您将遇到类似的问题。
  • 你倒退了。您的代码断言 每个 字符不是空格,而是一个数字 一个单词字符。您应该检查 is 是否有一个数字/单词字符,而不是是否有一个 不是 的字符。
  • 哦,是的!感谢您的帮助。

标签: python python-3.x


【解决方案1】:

正如 cmets 所说,您正在检查每个 char 是否为数字(如果是,则第二个 elif 失败,因为您检查它是否为字符)。这不是您想要做的,您只是想确保整个字符串包含一个数字。

您可以为此使用regex

if re.search(regex, password):
    # regex found something
else:
    # no match

我个人认为最好告诉用户所有失败的事情(不仅仅是第一次失败)。

import re

def setPassword(profilePassword):
    msg = ""
    if re.search(r' ', profilePassword):
        msg += "* Your password can't contain spaces!\n"

    if not re.search(r'\d', profilePassword):
        msg += "* Your password has to contain at least one number!\n"

    if not re.search(r'[a-z]', profilePassword):
        msg += "* Your password has to contain at least one lowercase letter!\n"

    if not re.search(r'[A-Z]', profilePassword):
        msg += "* Your password has to contain at least one uppercase letter!\n"

    if msg == "":
        print("Setting password was successfull")
    else:
        print("Setting password was not successfull due to following reasons:")
        print(msg)



setPassword("")
setPassword(" ")
setPassword("a")
setPassword("A")
setPassword("1")

setPassword("asd123")

setPassword("aA1")

while True:
    profilePassword = input("Password: ")
    if profilePassword == "":
        print("Your password can't be blank!")
        continue
    else:
        pass
    setPassword(profilePassword)

在搜索时也发现了这个:Checking the strength of a password (how to check conditions)

【讨论】:

    【解决方案2】:

    不要循环。将您的密码转换为设置和检查交叉点,如下所示:

    digits = set("0123456789")
    pw = set("password")
    if not digits.intersection(pw):
         # no digits in password 
    

    【讨论】:

      猜你喜欢
      • 2015-03-28
      • 1970-01-01
      • 2013-06-07
      • 2012-11-02
      • 1970-01-01
      • 2020-02-07
      • 2021-06-28
      • 2021-09-13
      • 2014-04-21
      相关资源
      最近更新 更多