我正在尝试创建一个函数来检测字符串有多少个数字、字母、空格等。
这是我到目前为止所拥有的:
def count(x):
length = len(x)
digit = 0
letters = 0
space = 0
other = 0
for i in x:
if x[i].isalpha():
letters += 1
elif x[i].isnumeric():
digit += 1
elif x[i].isspace():
space += 1
else:
other += 1
return number,word,space,other
但它不起作用:
>>> count(asdfkasdflasdfl222)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
count(asdfkasdflasdfl222)
NameError: name 'asdfkasdflasdfl222' is not defined
我的代码有什么问题,如何将其改进为更简单、更精确的解决方案?
这是另一种选择:
s = 'some string'
numbers = sum(c.isdigit() for c in s)
letters = sum(c.isalpha() for c in s)
spaces = sum(c.isspace() for c in s)
others = len(s) - numbers - letters - spaces
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)