首页 > 解决方案 > Python初学者任务

问题描述

我正在努力学习python。我已经到了我们正在学习“for”循环的地步,并且有点咸菜。第一项任务是构建一个计算所有空格的函数,我的解决方案是:

def count_spaces(s):
    cnt = 0
    for char in s:
        if char == " ":
            cnt = cnt+1
    return cnt

现在我正在尝试构建一个新函数,它可以接受字符串、字符并返回特定字符的计数

例如:

print(count_char("Hello world!", " ")

屏幕将显示 1(找到 1 个空格)这是我卡住的地方:

def count_char(s, c):
    s=[...]
    num = 0
    for x in s:
        if x == x:
            num = s.count(c)
    return num

它只返回 0 ....

请帮忙

标签: pythonfunctionloops

解决方案


你在你s的函数开始时覆盖你的论点:

   s = [...]

这使得其余的事情变得不可能。不要那样做!:)

如果您被允许使用该count方法(就像您的代码正在做的那样),您根本不需要for循环:

def count_char(s: str, c: str) -> int:
    """The number of character c in string s."""
    return s.count(c)

如果您想在不使用 的情况下执行此操作count,则可以完全像您的count_space函数一样编写它,但将 替换" "c参数:

def count_char(s: str, c: str) -> int:
    """The number of character c in string s."""
    cnt = 0
    for char in s:
        if char == c:
            cnt = cnt+1
    return cnt

或者您可以将for理解与sum函数一起使用:

def count_char(s: str, c: str) -> int:
    """The number of character c in string s."""
    return sum(1 if char == c else 0 for char in s)

或者您可以使用计数器:

from collections import Counter

def count_char(s: str, c: str) -> int:
    """The number of character c in string s."""
    return Counter(s)[c]

推荐阅读