如何在 python 中要求输入字符串为大写字母和数字?

How to require a capital letter and a number for an input string in 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: ")

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

编辑: 我不想知道如何制作密码要求程序。我特别想知道为什么 "and not" 不起作用。**

我特别想知道为什么 "and not" 不工作

"1234567890" not in password

"1234567890" in password 的否定,对于 passwordstr 正在检查 "1234567890" 是否是 [=14 的 substring =]. 考虑一下:

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

要检查第一个 str 中的任何字符是否出现在第二个 str 中,您可以检查交集是否不为空 - 只需将第二个 str 变成 set,与 first 相交,并对结果使用 bool 函数,如果第一个 str 的至少一个字符出现在第二个中,则得到 True,否则得到 False

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

我昨天刚好写了这个。 调味:-)

import re
import getpass
while True:
    pwd = getpass.getpass('please enter a password: ')
    if len(pwd) >= 8 and re.search('[0-9]', pwd) and re.search('[A-Z]', pwd):
        if pwd != getpass.getpass('please reenter password: '):
            print('passwords do not match')
        else:
            break
    else:
        print('passwords must contain 8 characters and at least one uppercase letter and one digit')

print('approved pwd:', pwd)