简体   繁体   English

检查字符串中的任何字符是否为字母数字

[英]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? for循环迭代仍然在第一个代码中发生,那么为什么不抛出错误呢? The second code throws: 第二个代码抛出:

Traceback (most recent call last): File "", line 18, in TypeError: 'bool' object is not iterable 回溯(最近一次调用最后一次):TypeError中的文件“”,第18行:'bool'对象不可迭代

In your second function you apply any to a single element and not to the whole list. 在第二个函数中,您将any应用于单个元素,而不是整个列表。 Thus, you get a single bool element if character i is alphanumeric. 因此,如果字符i是字母数字,则会得到一个bool元素。

In the second case you cannot really use any as you work with single elements. 在第二种情况下,当您使用单个元素时,您无法真正使用any一个。 Instead you could write: 相反,你可以写:

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

Which will be more similar to your first case. 哪个更类似于你的第一个案例。

any() expects an iterable. any()需要一个可迭代的。 This would be sufficient: 这就足够了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM