以下逻辑是否有助于从字符串中查找子字符串的出现次数?

时间:2018-12-22 08:06:55

标签: python

为了给hackerrank挑战以打印子字符串在给定字符串中出现的次数,我编写了附加逻辑。 但我一直收到0有输出。请就缺少的逻辑分享评论。

打印给定字符串中子字符串出现的次数

def count_substring(string, sub_string):
    count = 0
    for i in range(0,len(string)):
        if(sub_string== string[i:i+len(sub_string)]):
            count= ++count 
    return count
if __name__ == '__main__':
    string = input().strip()
    sub_string = input().strip()

    count = count_substring(string, sub_string)
    print(count)

字符串和sub_string的输入为 ABCDCDC,CDC

预期输出为2,但实际结果为0

2 个答案:

答案 0 :(得分:0)

count=++count在Python中不起作用(例如,Behaviour of increment and decrement operators in Python),应该为count+=1,然后您的代码才能按预期工作。

答案 1 :(得分:-1)

错误位于您的count = ++count行中 将此更改为count += 1