How can I check for at least 5 digits and 5 special characters in a Python string?

October 26, 2025 3 answers
Asked by CuriousCoder92
I'm working on a Python program where I need to validate a password. Specifically, I want to ensure that it contains at least 5 digits and 5 special characters. Currently, I'm not sure how to achieve this beyond simply checking for numbers and special characters. Here's a snippet of my code: ```python # making the password input password = input("Enter your password: ") findnum = re.search("[0-9]", password) # Finds a number findspecialchar = any(not char.isalnum() for char in password) # Checks for special characters findupper = any(char.isupper for char in password) # Finds uppercase letters # Validations if len(password) = 25: print("Your password must be 25 characters or less.") elif findnum and findspecialchar and findupper: # Trouble checking counts correctly if len(findnum) < 5: print("Your password must contain at least 5 digits.") print("Your password is strong enough if it contains special characters and uppercase letters.") else: print("Your password isn't strong enough.") ``` In the error log, it mentions an issue with argument types. Can someone suggest a better way to handle this counting process?

Answers

TechGuru88
Instead of using `re.search`, you might want to try `re.findall()`. This will give you all matches in the string, making it easier to count the digits. Here's a quick example: ```python num_count = len(re.findall(r'[0-9]', password)) special_char_count = len(re.findall(r'[^a-zA-Z0-9]', password)) ``` This way, you can easily check if `num_count` and `special_char_count` are both 5 or more.
Reply to this answer
DevLover42
Creating a function would definitely help organize your code. You can loop through each character, tallying the amounts of digits and special characters. Remember to check the length restriction before validating counts.
Reply to this answer
CodeMaster2021
You could simplify your approach using a for loop to count the digits and special characters. Just iterate over each character in the string and use counters: ```python num_count = 0 special_char_count = 0 for char in password: if char.isdigit(): num_count += 1 elif not char.isalnum(): special_char_count += 1 if num_count >= 5 and special_char_count >= 5: print("Password is valid.") else: print("Password must have at least 5 digits and 5 special characters.") ``` This keeps your code straightforward and efficient.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions