Python 中的 xxx is not defined 是什么意思?(尝试计算数字和字母)
我正在尝试写一个函数,用来检测一个字符串里面有多少个数字、字母、空格和其他字符。你知道我的代码哪里出错了吗?谢谢!
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].isdigit():
digit += 1
elif x[i].isspace():
space += 1
else:
other += 1
return number,word,space,other
它显示了这个错误:
>>> count(sdfjalfkjaslfkjs1211)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
count(sdfjalfkjaslfkjs1211)
NameError: name 'sdfjalfkjaslfkjs1211' is not defined
如果我输入 count('sdfjalfkjaslfkjs1211'),它就会出现这个错误:
>>> count('sdfjalfkjaslfkjs1211')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
count('sdfjalfkjaslfkjs1211')
File "C:/Python34/1.py", line 8, in count
if x[i].isalpha():
TypeError: string indices must be integers
3 个回答
0
这是因为Python编译器能够理解
如果你想把它当作一个字符串使用,就需要在某个地方定义它,或者把它放在引号里。
4
它把 sdfjalfkjaslfkjs1211
当成了一个变量名。如果你想让它变成字符串,就把它放在引号里。
1
除了没有把字符串作为参数传递之外,你还有其他问题:
你在遍历元素的同时还试图进行索引,这样是不对的:
number,word
在你的代码中并不存在。if x[i].isalpha():
这里的 i
是一个字符串,而不是一个整数,你应该用整数来索引字符串,而不是用其他字符串。
这样做是可以的:
def count(x):
digit = 0
letters = 0
space = 0
other = 0
for ele in x:
if ele.isalpha():
letters += 1
elif ele.isdigit():
digit += 1
elif ele.isspace():
space += 1
else:
other += 1
return digit, x, space, other, letters
如果你想进行索引,可以使用 for i in range(length):
。
In [6]: count("sdfjalfkjaslfkjs1211")
Out[6]: ('sdfjalfkjaslfkjs1211', 0, 0, 4, 16)