-1

I have a scenario where I dont want to use regex. I have a string of password. I want to check condition like , it should contain alphabet, numberic , capital letter, small letter, special characters. How to achieve this without regex? What would be the fastest way to do this? I have made list of a-z and A-Z and 0-9 and special characters. But that is consuming time to write all things in list. Thanks!

  • 1
    Welcome to Stack Overflow! In order for us to help you best, please read and create an [MCVE](https://stackoverflow.com/help/minimal-reproducible-example). – m13op22 Nov 20 '19 at 15:29
  • https://stackoverflow.com/questions/41117733/validation-of-a-password-python could help you on this. – Raj Paliwal Nov 20 '19 at 15:30

3 Answers3

4

You can use any to check if any of the characters in the password are in one of the character sets you describe. Then wrap that in all to ensure one of each of your requirements are satisfied.

import string

def validate_password(password):
    char_sets = {string.ascii_lowercase,
                 string.ascii_uppercase,
                 string.digits,
                 string.punctuation}
    return all(any(letter in char_set for letter in password) for char_set in char_sets)

For example

>>> validate_password('password')
False
>>> validate_password('Password1!')
True
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

You can use a set of tests like these:

pw = 'Ab1!'
has_alpha = any([x.isalpha() for x in pw])
has_num = any([x.isdigit() for x in pw])
has_upper = any([x.isupper() for x in pw])
has_lower = any([x.islower() for x in pw])
has_symbol = any([not x.isalnum() for x in pw])

is_proper_pw = has_alpha and has_num and has_upper and has_lower and has_symbol
mrhd
  • 1,036
  • 7
  • 16
0

Perhaps by comparing the ASCII values of the characters in the password? Something like:

pw = "Hello"

# convert password to ASCII numbers
pw_to_ascii = [int(ord(c)) for c in pw]

# ASCII range for capital letters
cap_range = range(65,90)

# CHeck for capitals
for c in cap_range:
    if c in pw_to_ascii:
        print("Contains capital.") # replace with your desired action

You could do additional checks for special characters by just checking different ranges. Its a naive approach but does the job. If you want to limit the possible characters, as most passwords do (such as spaces), you could just add a range to check for those specifically.

mu_Lah
  • 1
  • 2