Python程序如何计算字母c出现的次数 [英] Python Program how to count number of times the letter c shows up

查看:157
本文介绍了Python程序如何计算字母c出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分配:

返回字符串中字符 c 的出现次数 s
忽略大小写。使用循环。不要使用内置字符串方法 count
做类似的事情。这个想法是学习编写循环。在比较$ s c 的字符时,
应该忽略大小写。

Return the number of occurrences of character c in string s, ignoring case. Use loops. Do not use the in-built string method count, which does a similar thing. The idea is to learn to write loops. You should ignore case when comparing a character of s with c.

我的尝试

 def countletter(s, c): #BAD
     count = 0
     for c in s:
        if c == c:
        count += 1
        return count

我在正确的轨道上吗?在主程序中测试它时,似乎会出现一些断言错误。

Am I on the right track? I seem to get some assertion errors when I test it in the main...

推荐答案

您的返回在错误的位置。因此,您的函数实际上仅在一次迭代后返回。

your return is at wrong place. So your function is actually returning only after one iteration.

此外,您也不应该在变量名中使用 c 循环,请使用一些其他变量,因为它将替换从函数调用中获得的 c 的值,并由 for-loop

Also you should not use the variable name c in for loop, use some different variable, as it replaces the value of c recieved from the function call with the current character being fetched by the for-loop.

def countletter(s, c): #BAD
    count = 0
    for x in s:
        if x.lower() == c.lower():
            count += 1
    return count


print countletter("abcdefFf","F") #prints 3
print countletter("a","A")        #prints 1

这篇关于Python程序如何计算字母c出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆