Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement to check whether a string has a capital letter, a lower case letter and a number [closed]

Tags:

python

Can someone give an idea on how to test a string that:

  • contains at least one upper case letter
  • contains at least one lower case letter
  • contains at least one number
  • has a minimal length of 7 characters
like image 216
AmaChurLOL Avatar asked Jun 17 '13 04:06

AmaChurLOL


People also ask

How do you check if a string has a lowercase letter?

The islower() method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False.

How do you know if a string is uppercase or lowercase?

To check if a letter in a string is uppercase or lowercase use the toUpperCase() method to convert the letter to uppercase and compare it to itself. If the comparison returns true , then the letter is uppercase, otherwise it's lowercase. Copied!

How do you check if a string contains uppercase and lowercase in python?

Python Isupper() To check if a string is in uppercase, we can use the isupper() method. isupper() checks whether every case-based character in a string is in uppercase, and returns a True or False value depending on the outcome.

How do you check if a variable has a capital letter in Python?

Introduction to the Python String isupper() methodThe string isupper() method returns True if all cased characters in a string are uppercase. Otherwise, it returns False . If the string doesn't contain any cased characters, the isupper() method also returns False .


1 Answers

if (any(x.isupper() for x in s) and any(x.islower() for x in s) 
    and any(x.isdigit() for x in s) and len(s) >= 7):

Another way is to express your rules as a list of (lambda) functions

rules = [lambda s: any(x.isupper() for x in s), # must have at least one uppercase
        lambda s: any(x.islower() for x in s),  # must have at least one lowercase
        lambda s: any(x.isdigit() for x in s),  # must have at least one digit
        lambda s: len(s) >= 7                   # must be at least 7 characters
        ]

if all(rule(s) for rule in rules):
    ...

Regarding your comment. To build an error message

errors = []
if not any(x.isupper() for x in password):
    errors.append('Your password needs at least 1 capital.')
if not any(x.islower() for x in password):
    errors.append(...)
...

if errors:
    print " ".join(errors)
like image 89
John La Rooy Avatar answered Oct 27 '22 02:10

John La Rooy