Home > database >  Python program for upper, lower, numbers and combination
Python program for upper, lower, numbers and combination

Time:02-26

I'm trying to write a program that user input a random text, and it will print out if it has lower letter, upper letter and/or numbers. When ever i try to input a combination of numbers and letter it won't print. Could someone help me with it?

string = input("write something here: ")
if string.isalpha() and not string.isupper():
    print("Has letter")
if string.isupper():
    print("Has only upper letters")
if string.islower():
    print("Has only lower letters")
if string.isdigit():
    print("Has numbers")
if string.isalpha() and string.isdigit():
    print("Has numbers and letters")

CodePudding user response:

When ever i try to input a combination of numbers and letter it won't print.

An input like test123 will not print out Has numbers and letters because the function isalpha is checking if ALL characters are alphabetical (e.g. abc but not abc1), while the function isdigit tests if ALL characters are numeric (e.g. 123 but not 123x)

The solution here is to use the function str.isalnum (is alpha-numeric):

# passes for: abc123, abc, 123
if string.isalnum():
    print("Has numbers and/or letters")

Or, if you want to exclude if it has only numbers or only letters:

# passes for: abc123
if string.isalnum() and not string.isdigit() and not string.isalpha():
    print("Has both numbers and letters")

CodePudding user response:

It's because functions like isalpha and isdigit will only return True if they contain ONLY letters or numbers. Not both.

So isalpha("ldshfldhf") will return True, but isalpha("ldshfldhf12") will not return True.

And likewise isdigit("123490") will return True but isdigit("az123490") will return False.

So none of the if statements you have above will return True, so nothing will print.

CodePudding user response:

string = input("enter random text here:")

if string.isalnum():
    print("It is alphanumeric character")
    
    if string.isalpha():
        print("It is alphabet character")
        
        if string.islower():
            print("It is lowercase alphabet character")
        
        elif string.isupper():
            print("It is a uppercase alphabet character")
    else:
      print("It is a digit")
            
elif string.isspace():
    print("It is a space character")
        
        
else:
  print("It is a special character")
  • Related