简体   繁体   中英

How to have string functions check individual characters instead of whole strings?

I'm new at Python coding and I am trying to build a simple password checker. Requirements for passwords are:

at least 8 characters at least one capital letter at least one lowercase letter at least one digit CANNOT start with a letter must contain at least one character that isn't a letter or a digit.

Here is the code that I have created so far:

def main():
  letters = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'
  pword = input('Please enter a password')
  t = True
  while t:
    if len(pword) < 8:
      break
    
    if pword.isupper() == False:
      break
    
    if pword.islower() == False:
      break
    
    if pword.isdigit() == False
      break
    
    if pword[0] == letters:
      break
    
    if pword.isalpha() == True or pword.isdigit() == True:
      break
    
  if t:
    print("INVALID")
  
main()

I think for the most part I've got everything down but I'm having a hard time figuring out how to have isupper, islower, and isdigit not check to see if the whole string is uppercase, lowercase or all digits. I only want them to check to see if the string contains at least one uppercase, lowercase, and digit. I also need to ensure the program checks to see if at least one character is anything except a number or a digit.

You can use if with several conditions combined with and :

def main():
  letters = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'
  pword = input('Please enter a password')
  if (len(pword)>8) and (any(x for x in pword if x.isupper())) and (any(x for x in pword if x.islower())) and (any(x for x in pword if x.isdigit())) and (any(x for x in pword if not x.isalnum())):
    # good password
  else:
    # problem man

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM