计数变量递增

2024-09-30 01:33:51 发布

您现在位置:Python中文网/ 问答频道 /正文

def countDog1(st):
    count = 0
    for word in st.lower().split():
        if word == 'dog':
            count += 1
    return count

我想增加count的值,但它只起作用一次。你知道吗


Tags: inforreturnifdefcountlowerword
2条回答

我假设意外行为是由字符串中的非字母数字字符引起的:

'hello dog dog!'.lower().split()

退货

['hello', 'dog', 'dog!']

因此“狗”只会被计算一次。下面是一个如何用re解决这个问题的例子:

import re

def countDog1(st):
    count = 0
    for word in st.lower().split():
        if word == 'dog':
            count += 1
    return count

print('Function countDog1: ' + str(countDog1('hello dog I am a dog!')))

def countDog2(st):
    count = 0
    st = re.sub(r'([^\s\w]|_)+', '', st)
    for word in st.lower().split():
        if word == 'dog':
            count += 1
    return count

print('Function countDog2: ' + str(countDog2('hello dog I am a dog!')))

输出:

Function countDog1: 1
Function countDog2: 2

你在问题中写的函数似乎起作用了。一定要把回程板缩进好。您可能在代码中将其缩进了一个级别。你知道吗

相关问题 更多 >

    热门问题