Checking if any character in a string is alphanumeric

最后都变了- 提交于 2020-06-24 08:49:33

问题


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


回答1:


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.




回答2:


any() expects an iterable. This would be sufficient:

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


来源:https://stackoverflow.com/questions/44057069/checking-if-any-character-in-a-string-is-alphanumeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!