Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if any character in a string is alphanumeric

I want to check if any character in a string is alphanumeric. I wrote the following code for that and it's working fine:

s = input()

temp = any(i.isalnum() for i in s)
print(temp)

The question I have is the below code, how is it different from the above code:

for i in s:
    if any(i.isalnum()):
        print(True)

The for-loop iteration is still happening in the first code so why isn't it throwing an error? The second code throws:

Traceback (most recent call last): File "", line 18, in TypeError: 'bool' object is not iterable

like image 550
rachitmishra25 Avatar asked May 18 '17 20:05

rachitmishra25


People also ask

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

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 all characters in a string are alphabets?

The isalpha() method returns True if all the characters are alphabet letters (a-z). Example of characters that are not alphabet letters: (space)!

How do you check if the given string is alphanumeric in Java?

isAlphanumeric() is a static method of the StringUtils class that is used to check if the given string only contains Unicode letters or digits. The method returns false if the string contains Unicode symbols other than Unicode letters and digits. The method returns false if the input string is null .


1 Answers

In your second function you apply any to a single element and not to the whole list. Thus, you get a single bool element if character i is alphanumeric.

In the second case you cannot really use any as you work with single elements. Instead you could write:

for i in s:
    if i.isalnum():
        print(True)
        break

Which will be more similar to your first case.

like image 161
JohanL Avatar answered Sep 23 '22 10:09

JohanL