首页 > 解决方案 > 如何在 python 中为输入字符串要求大写字母和数字?

问题描述

password = input(str("Please enter a password with a capital letter and a number: "))
for char in password:
    if password.islower() and "1234567890" not in password:
        print("Your password will need to have at least one number and at least one capitalized letter")
        password = input("Please enter another password: ")

**如果输入的密码没有数字或大写,则会打印错误短语,但如果输入中使用大写,则即使输入仍然缺少数字,错误字符串也不会运行。如果输入有数字但没有大写字母,则相同。正如您可能知道的那样,我希望输入时需要一个大写字母和一个数字。谢谢。

编辑:我不想知道如何制作密码要求程序。我特别想知道为什么“而不是”不起作用。**

标签: pythonpython-3.xpasswords

解决方案


我特别想知道为什么“而不是”不起作用

"1234567890" not in password

是它的否定,"1234567890" in passwordpassword正在str检查是否"1234567890"是 的子字符串password考虑一下:

print("123" in "123123123")  # True
print("123" in "1")  # False
print("123" in "321")  # False

str要检查第二个中是否存在任何字符,str您可以检查交叉点是否不为空 - 只需将第二个str变为set,与第一个获取交叉点,然后bool对结果使用函数,从而获取True第一个 str 的至少一个字符是否存在于第二和False其他:

x = "1234567890"
y = "sometextandnumber0"
print(bool(set(y).intersection(x)))  # True

推荐阅读