Python - Check if a string contains a digit [duplicate]

末鹿安然 提交于 2021-01-28 03:41:23

问题


I am making a function that uses a while True loop to ask the user to input a password that passes the criteria; min8-15max characters in length and includes at least one integer. I am stumped on how to properly check the input for an integer.

My program:

def enterNewPassword():
    while True:
        pw = input('Please enter a password :')
        for i in pw:
            if type(i) == int:
                if len(pw) >= 8 and len(pw) <= 15:
                    break
        if int not in pw:
            print('Password must contain at least one integer.')
        if len(pw) < 8 or len(pw) > 15:
            print('Password must be 8 and no more than 15 characters in length.')
    return pw

回答1:


Try:

if not any(c.isdigit() for c in pw)

Instead of

if int not in pw:
    print('Password must contain at least one integer.')

int is a type object and you want check the presence of characters 0-9.




回答2:


You can use regular expressions eg:

    import re
    password = "hello"
    matches = re.findall('[0-9]', password)
    if len(matches) < 1:
        print "Password must contain at least one integer"


来源:https://stackoverflow.com/questions/33205288/python-check-if-a-string-contains-a-digit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!