练习7.9在"如何像计算机科学家(python)一样思考"中测量字符串中字符的出现次数

1 python string

问题是如何编写一个程序来测量一个字符在python中以一般化的方式出现在字符串中的次数.

我写的代码:

def countLetters(str, ch):
   count=0
   index=0
   for ch in str:
     if ch==str[index]:
       count=count+1
     index=index+1
   print count
Run Code Online (Sandbox Code Playgroud)

当我使用这个函数时,它测量字符串的长度,而不是字符串中字符出现的次数.我做错了什么?编写此代码的正确方法是什么?

Hug*_*ell 5

你正在覆盖'ch'变量:

def countLetters(str, ch):
#                      ^ the character you are looking for
    count=0
    index=0
    for ch in str:
#        ^ the string character you are trying to check
        if ch==str[index]:  # ???
            count=count+1
        index=index+1
    print count
Run Code Online (Sandbox Code Playgroud)

(另外,返回值通常比打印它更有用).

内置方法是str.count:

"aaabb".count("a")  -> 3
Run Code Online (Sandbox Code Playgroud)

如何重写代码:

def countLetters(search_in, search_for):
    count = 0
    for s in search_in:    # iterate by string char, not by index
        if s==search_for:
            count += 1
    return count
Run Code Online (Sandbox Code Playgroud)

和一个快速的pythonic替代品:

def countLetters(search_in, search_for):
    return sum(1 for s in search_in if s==search_for)
Run Code Online (Sandbox Code Playgroud)