Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have to check if the string contains: alphanumeric, alphabetical , digits, lowercase and uppercase characters

def fun(s):
    for i in s:
        if i.isalnum():
            print("True")
        if i.isalpha():
            print("True")
        if i.isdigit():
            print("True")
        if i.isupper():
            print("True") 
        if i.islower():
            print("True")
s=input().split()
fun(s)

why it prints true only once even though it is in a for loop

like image 748
palak Avatar asked Jul 13 '18 08:07

palak


People also ask

How do you check if a character in a string is alphanumeric?

Python string isalnum() function returns True if it's made of alphanumeric characters only. A character is alphanumeric if it's either an alpha or a number. If the string is empty, then isalnum() returns False .

How do you check if a string has any alphanumeric in Python?

isalnum() is a built-in Python function that checks whether all characters in a string are alphanumeric. In other words, isalnum() checks whether a string contains only letters or numbers or both. If all characters are alphanumeric, isalnum() returns the value True ; otherwise, the method returns the value False .

How do you check if a character in a string is uppercase Python?

isupper() In Python, isupper() is a built-in method used for string handling. This method returns True if all characters in the string are uppercase, otherwise, returns “False”.


3 Answers

If you want to check if the whole string contains those different characters types then you don't actually have to loop through the string. You just can use the any keyword.

def fun(s):
    if any(letter.isalnum() for letter in s):
        print("Is alphanumeric")
    if any(letter.isalpha() for letter in s):
        print("Is alpha")
    if any(letter.isdigit() for letter in s):
        print("Is digit")
    if any(letter.isupper() for letter in s):
        print("Is upper")
    if any(letter.islower() for letter in s):
        print("Is lower")

s=str(input())
fun(s)
like image 112
Tom Dee Avatar answered Nov 07 '22 09:11

Tom Dee


string = input()

print (any(c.isalnum() for c in s))
print (any(c.isalpha() for c in s))
print (any(c.isdigit() for c in s))
print (any(c.islower() for c in s))
print (any(c.isupper() for c in s))
like image 34
Sina Cengiz Avatar answered Nov 07 '22 09:11

Sina Cengiz


if __name__ == '__main__':
    s = input()
    print(any(c.isalnum()  for c in s))
    print(any(c.isalpha() for c in s))
    print(any(c.isdigit() for c in s))
    print(any(c.islower() for c in s))
    print(any(c.isupper() for c in s))

code is updated for python 3 using any function without uing if else

like image 41
Md. Rizwan Rabbani Avatar answered Nov 07 '22 11:11

Md. Rizwan Rabbani