Build a Secure Password Strength Checker in Python
A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.
Python code
26 linesimport re
def password_strength(password: str) -> str:
score = 0
if len(password) >= 8:
score += 1
if re.search(r'[a-z]', password):
score += 1
if re.search(r'[A-Z]', password):
score += 1
if re.search(r'\d', password):
score += 1
if re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
score += 1
if score <= 2:
return "Weak"
elif score == 3:
return "Moderate"
else:
return "Strong"
if __name__ == "__main__":
test_passwords = ["hello", "Password123!", "weak", "Str0ng!Pass"]
for pwd in test_passwords:
print(f"'{pwd}' -> {password_strength(pwd)}")
Output
'hello' -> Weak
'Password123!' -> Strong
'weak' -> Weak
'Str0ng!Pass' -> Strong
How it works
The function assigns one point for each of five criteria: length >=8, lowercase, uppercase, digit, and a special character. The score determines the strength rating. Using re.search with character classes makes checks concise and readable. This approach gives immediate feedback without external libraries.
Common mistakes
- Forgetting to check for whitespace or empty strings, which would score 0 and return Weak.
- Using a weak regex for special characters that misses common symbols like `@` or `#`.
- Not handling Unicode or non-ASCII characters, which may cause false positives.
Variations
- Use a single regex with lookaheads for a one-pass check.
- Add a blacklist check against common weak passwords.
Real-world use cases
- Enforcing minimum password strength during user registration in a web app.
- Validating password reset tokens to prevent reuse of weak passwords.
- Auditing existing stored hashes by rechecking strength of known plaintexts.
Sponsored
Keep learning
Related tutorials and quizzes for this topic.