【发布时间】:2014-09-12 17:31:35
【问题描述】:
我正在尝试制作一个函数来检测字符串中有多少个数字、字母、空格和其他内容。
这是我目前所拥有的:
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
我的代码有什么问题,如何将其改进为更简单、更精确的解决方案?
【问题讨论】:
-
您的代码做了哪些不该做的事情?它应该做什么?您的调查发现了差异的原因是什么?
-
...这个问题作为错字都离题了(您错过了一对引号,请参阅this answer)(至少有一个MCVE...)|和ask many question at once(1:出了什么问题,2:如何改进)。问题2主要是基于意见的,更适合Code Review(14年有codereview吗?)|
-
我认为这个问题被赞成的唯一原因是因为this answer(它甚至不能解决错误(问题1),并且重写代码以不再使用函数)可能会有所帮助对很多人。 ||| This question was linked to on Meta.