gpt4 book ai didi

python - "How to Think Like a Computer Scientist (python)"中的练习 7.9 测量字符串中某个字符的出现次数

转载 作者:太空宇宙 更新时间:2023-11-04 07:47:01 25 4
gpt4 key购买 nike

问题是如何编写一个程序来测量一个字符在 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

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

最佳答案

您正在覆盖“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

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

内置方法是str.count:

"aaabb".count("a")  -> 3

如何重写代码:

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

和一个快速的 pythonic 替换:

def countLetters(search_in, search_for):
return sum(1 for s in search_in if s==search_for)

关于python - "How to Think Like a Computer Scientist (python)"中的练习 7.9 测量字符串中某个字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4708273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com