Python 检查字符串中的任何字符是否为字母数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44057069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if any character in a string is alphanumeric
提问by rachitmishra25
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:
for 循环迭代仍在第一个代码中发生,为什么它不抛出错误?第二个代码抛出:
Traceback (most recent call last): File "", line 18, in TypeError: 'bool' object is not iterable
回溯(最近一次调用):文件“”,第 18 行,在 TypeError 中:“bool”对象不可迭代
采纳答案by JohanL
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.
在您的第二个函数中,您应用于any
单个元素而不是整个列表。因此,如果字符i
是字母数字,您将得到一个 bool 元素。
In the second case you cannot really use any
as you work with single elements. Instead you could write:
在第二种情况下,any
当您使用单个元素时,您无法真正使用。相反,你可以写:
for i in s:
if i.isalnum():
print(True)
break
Which will be more similar to your first case.
这将更类似于您的第一个案例。
回答by Stephen Rauch
any()
expects an iterable. This would be sufficient:
any()
期待一个迭代。这就足够了:
isalnum = False
for i in s:
if i.isalnum():
isalnum = True
break
print(isalnum)