How do you use: isalnum, isdigit, isupper to test each character of a string? [closed]

两盒软妹~` 提交于 2019-12-01 13:36:21

问题


I am trying to make a password strength simulator which asks the user for a password and then gives back a score.

I am using:

islanum() 
isdigit()
isupper() 

to try and see how good the inputted password is.

Instead of returning boolean values, I want this to assess each characters of the password, and then the program to add up all the "True" values and turn it into a score. EXAMPLE CODE:

def upper_case():
    points = int(0)
    limit = 3
    for each in pword:
        if each.isupper():
            points = points + 1
            return points
        else:
            return 0

Any help would be much appreciated!! THANKS!!


回答1:


.isalnum(), .isupper(), .isdigit() and friends are methods of the str type in Python and are called like this:

>>> s = "aBc123"
>>> s[0].isalnum()
True
>>> s[1].isupper()
True
>>> s[3].isdigit()
True

Simple getscore() Function:

s = "aBc123@!xY"

def getscore(s):
    score = 0
    for c in s:
        if c.isupper():
            score += 2
        elif c.isdigit():
            score += 2
        elif c.isalpha():
            score += 1
        else:
            score += 3
    return score

print getscore(s)

Output:

13

Better Version:

s = "aBc123@!xY"


def getscore(s):
    return len(s) + len([c for c in s if c.isdigit() or c.isupper() or not c.isalpha()])

print getscore(s)

Output:

17



回答2:


You can use something like

password = "SomePa$$wordYouWantToTest"
score = len([char for char in password if str(char).isupper() or str(char).isdigit() or not str(char).isalnum()])

This will count all upper chars, all digits and all non alphanumeric chars in password giving an integer

Output of the test:

>>>score
8



回答3:


Just another way of solving using regex:

#!/usr/bin/python
import re
def password_strength(p):
    score = 0
    if re.search('\d+',p):
        score = score + 1
    if re.search('[a-z]',p) and re.search('[A-Z]',p):
        score = score + 1
    if re.search('[$#@!]', p):
        score = score + 1
    return score

print password_strength('Jac@kpasswor01')


来源:https://stackoverflow.com/questions/20582277/how-do-you-use-isalnum-isdigit-isupper-to-test-each-character-of-a-string

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