字符串中的整数

2024-10-02 14:24:03 发布

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

编写一个名为enterNewPassword的函数。此函数不接受参数。它会提示用户输入密码,直到输入的密码包含8-15个字符(至少包括一个数字)。每当密码在这两个测试中的一个或两个都失败时告诉用户。在

但我似乎无法找到一个数字的答案。这就是我到目前为止的想法。在

你能帮我检查一下输入的密码里有没有数字吗?在我觉得应该放点东西的地方有问号。谢谢您!在

def enterNewPassword():

    password = input("Enter a password: ")

    if len(password) < 8:

        print("Your password does not contain 8-15 characters.")

    if len(password) > 15:

        print("Your password contains more than 15 characters.")

    if ??? not in password:

        print("Your password does not contain a digit.")

    if ??? in password and 8 <= len(password) >= 15:

        print("Good password!")

enterNewPassword()

Tags: 函数用户in密码yourlenifnot
2条回答

如果要检查字符串中的数字,可以使用any()方法。在

any(c.isdigit() for c in password)

如果被检查的条件至少返回一次True,那么any几乎都会返回True,在本例中使用“c.isdigit()”

isdigit()是string对象中可用的方法,因此使用该调用几乎可以检查每个字符是否为数字。这里还有一个关于isidigit的文档。在

这是any()上的文件

def enterNewPassword():

    while True:    # infinite loop
        s = input("\n\nEnter password: ")
                                 # count digits in string
        if 15 < len(s) < 8 or sum(str.isdigit(c) for c in s) < 1:
            print("Password must be 8-15 chars long and contain at least one digit:")
            continue
        else:
            print("The password is valid.")
            break

enterNewPassword()

Enter password: arte,alk;kl;k;kl;k;kl
Password must be 8-15 chars long and contain at least one digit:

Enter password: sunnyday
Password must be 8-15 chars long and contain at least one digit:


Enter password: rainyday
Password must be 8-15 chars long and contain at least one digit:


Enter password: cloudyday1
The password is valid .

相关问题 更多 >