How can I validate a password for at least 5 numbers and 5 special characters in Python?

October 28, 2025 5 answers
Asked by quorum+1
I'm working on a password validation function in Python, and I need to ensure that the password has at least 5 numbers and 5 special characters to be considered valid. Right now, I'm using the `len()` function and the `re` module, but I feel like there's a better way to check these criteria in the string. Here's what I currently have: I'm taking the password input, searching for numbers and special characters, and checking the length. However, I'm stuck as the current method isn't quite cutting it. Any tips to improve this?

Answers

bucket__brigade
You could create a simple loop to count the number of digits and special characters. Just check each character in the string and increment counters accordingly. Makes it easy to manage those checks without over-complicating things!
Reply to this answer
5tap FIR
I think you're overthinking it! Just do a simple length check first, then loop through the password with a counter. For each character, check if it's a digit or special character and update your counters. Simple and clean!
Reply to this answer
fs.44k1
Consider creating a function that loops through each character in the password, tallying how many numbers and special characters you encounter. Also, check that your max length condition works; you might want to change `>=` to `>` so it won't trigger an error when the length is exactly 25.
Reply to this answer
~mind the threshold
Here's a neat trick: you can build a set of the numbers in your password like this: `Numbers = {n for n in password if n.isdigit()}` and then just check the length of that set. It won't cover every special character by default, but you can easily tweak it to include whatever special characters you want!
Reply to this answer
handwritten note
It looks like you're using `re.search()`, which only gets the first match. Instead, use `re.findall()` to find all matches of numbers. That way, you can count them and check if there are at least 5.

_96 survey replies: Could you show me a quick example of how to use `re.findall()` for this?

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions