python字符串计数

2024-04-26 07:21:20 发布

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

如果字符串“cat”和“dog”在给定字符串中出现的次数相同,则返回True。在

这就是我想问的问题。我的代码是:

def cat_dog(str):
    count1 = 0
    count2 = 0

if 'dog' and 'cat' not in str:
    return True
for i in range(len(str)-1):
    if str[i:i+3] == 'cat':
        count1 += 1
    if str[i:i+3] == 'dog':
        count2 += 1
    if count1 == count2:
        return True
    else:
        return False

我知道这是不正确的,因为代码似乎并没有在整个字符串中循环,也没有找到猫和狗。不知道该如何纠正。在


Tags: and字符串代码intruereturnifdef
3条回答
if 'dog' and 'cat' not in str:

这不像你想的那样。Python这样解释:

^{pr2}$

第一部分总是正确的,因为'dog'是一个非空字符串,因此它归结为'cat' not in str。所以您实际上只检查字符串是否不包含'cat'。在

你想要这样的东西:

if 'dog' not in str and 'cat' not in str:

或者,相当于:

if not ('dog' in str or 'cat' in str):

或者,如果您有更多的测试要做,这是一个更紧凑的多对夫妇:

if not any(x in str for x in ('cat', 'dog', 'mouse', 'beaver')):

这会影响函数是否会进入循环,所以它可能会让你失望。在

另外,不要将变量命名为strstr是一个内置类型,您可能需要使用它,但不能使用,因为您已经重新分配了它。在

您来自函数的return的部分不应在for循环中。这就是循环过早退出的原因

def cat_dog(str):
    count1 = 0
    count2 = 0

    if 'dog' not in str and 'cat' not in str: # <= kindall pointed this out
        return True

    for i in range(len(str)-1):
        if str[i:i+3] == 'cat':
            count1 += 1
        if str[i:i+3] == 'dog':
            count2 += 1

    if count1 == count2:  # <= These shouldn't be part of the for loop
        return True
    else:
        return False

最后4行通常应写为

^{pr2}$

只需使用count方法来计算字符串的出现次数。在

>>> 'catdog'.count('cat') == 'catdog'.count('dog')
True
>>> 'catdogdog'.count('cat') == 'catdogdog'.count('dog')
False
>>> 

您需要在此代码之前添加一个条件,否则,如果输入字符串中不存在cat或{},则上述代码应返回true。在

^{pr2}$

相关问题 更多 >