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

六月ゝ 毕业季﹏ 提交于 2019-12-01 14:53:55

.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

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

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