字符串中的整数

时间:2015-10-17 03:26:58

标签: python python-3.4

编写一个名为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()

2 个答案:

答案 0 :(得分:1)

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

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

如果正在检查的条件至少返回True一次,那么任何将返回True,在这种情况下使用“c.isdigit()”

isdigit()是一个可用于字符串对象的方法,因此您几乎都要检查每个字符是否为该调用的数字。这是isidigit上的文档。

以下是any()

上的文档

答案 1 :(得分:0)

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 .