How to count number of substrings in python, if substrings overlap?
问题 The count() function returns the number of times a substring occurs in a string, but it fails in case of overlapping strings. Let's say my input is: ^_^_^-_- I want to find how many times ^_^ occurs in the string. mystr=input() happy=mystr.count('^_^') sad=mystr.count('-_-') print(happy) print(sad) Output is: 1 1 I am expecting: 2 1 How can I achieve the desired result? 回答1: New Version You can solve this problem without writing any explicit loops using regex. As @abhijith-pk's answer