当我尝试在我的树莓派上使用“list.count”函数时,它出现了
Name Error: name 'count' is not defined
我能做些什么吗?预先感谢您的任何帮助。我正在使用 Python。我刚开始使用 Python,在我的教程中它指出
>>>count(seq,'a')
“seq”是我之前输入的一系列字母。我希望它是为了计算序列中“a”的数量。453
非常感谢大家的快速回复和解答,我现在已经解决了这个问题。这是我提出的第一个在线问题,再次感谢您。 Markus Unterwaditzer 的第二个答案最终用'seq.count('a')'解决了问题
也感谢 DSM 找到了教程并解释了我遇到问题的原因。现在一切正常,我又开始学习我的第一门计算机语言。
请您参考如下方法:
啊。教程中的魔法在于
from string import *
行,这是不好的做法。它将字符串模块中的所有内容导入作用域,包括函数 string.count:
>>> print string.count.__doc__
count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
count也是字符串的方法,所以可以这样写
>>> 'aaa'.count('a')
3
通常是首选。在现代 Python 中,string 模块甚至没有 count 函数。
