2010-08-25 91 views
0

想要统计一个字母出现在字符串中的次数,这里有问题。任何帮助需要基本功能帮助 - Python

def countLetters(string, character): 
    count = 0 
    for character in string: 
     if character == character: 
      count = count + 1 
    print count 
+2

没错,'字符== character'即将所有的时间是非常真实的。 – 2010-08-25 00:37:20

+0

避免使用标准库名称('string')或builtins作为变量名称。 – 2010-08-25 01:02:50

+0

Theres在Python 2.7集合中包含一些有用的常用计算操作方法的“Counter”对象,如“most_common(n)”。 http://docs.python.org/library/collections.html?highlight=collections#counter-objects – monkut 2010-08-25 01:14:05

回答

1

您有那些character S中相同的变量名(这意味着他们将永远是平等的)。尝试:

def countLetters(string, character): 
    count = 0 
    for char in string: 
     if char == character: 
      count = count + 1 
    print count 

当然,这是一样的str.count()

+0

谢谢,这似乎是正确的,但我在空闲 >>> countLetters收到此错误(加利福尼亚州的一家) 回溯(最近通话最后一个): 文件 “”,1号线,在 countLetters(加州,a) NameError:name'california'没有定义 >>> – 2010-08-25 00:38:26

+0

没关系,愚蠢的评论。我不得不添加引号。 非常感谢 – 2010-08-25 00:39:17

3
if character == character: 

character永远等于character,因为他们是同一个变量。只需更改这些变量的名称即可。也许search_character

我也不会使用string作为变量名称,因为它是内置模块的名称。

9

其他人已经涵盖了你的功能的错误。这是另一种做你想做的事情的方法。 Python的内置字符串方法count()返回字符串出现次数。

x = "Don't reinvent the wheel." 
x.count("e") 

给出:

5 
+0

+1 - Pythonic,兄弟。 – duffymo 2010-08-25 00:40:56

+0

'x = reduce(operator.add,(char =='e'for char in“Do reinvent the wheel”))''? – 2010-08-26 14:14:07

+0

'sum(char =='e'for char in“重新发明轮子的另一种方式”)== 6'。比'reduce'和'operator.add'好得多。 – 2010-11-22 04:45:35