theRumblers100
theRumblers100

Reputation: 81

Python check if a input has a digit in it?

Im trying to see how i can see if a number is in a users input. i tried using .isdigit() but only works if its just a number. im trying to add it to a password checker. i also tried .isalpha() but didn't work. what have i done wrong and what do i need to add or change?

here is what i have

   password = input('Please type a password ')
   str = password
   if str.isdigit() == True:

    print('password has a number and letters!')
    else:
            print('You must include a number!')`

Upvotes: 3

Views: 3552

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You can use a generator expression and an isdigit() within the any function :

if any(i.isdigit() for i in password) :
       #do stuff

The advantage of using any is that it doesn't traverse the whole string and will return a bool value if it finds a digit for the first time!

It is equal to the fallowing function :

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

Upvotes: 5

Avinash Raj
Avinash Raj

Reputation: 174706

You may try re.search

if re.search(r'\d', password):
     print("Digit Found")

And don't use builtin data types as varible names.

Upvotes: 2

Related Questions