1

My problem is that python only counts occurrences with the amount of chars it searches.

a = "01010101"
print(a.count("010"))

Pythons string count here ends with 2. But from what i count there are 3 occurrences.

#x = "01010101"
#     --- <-- occurrence 1
#       ---  <-- occurrence 2
#         ---  <-- occurrence 3

May some one please point me in the right direction on what i do wrong, as i would require the result to be 3 not 2.

snapo
  • 684
  • 8
  • 23
  • 1
    Does this answer your question? [String count with overlapping occurrences](https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences) – Woodford Apr 19 '21 at 17:42

3 Answers3

1

You can use re for example:

import re

a = "01010101"

print(len(re.findall(r"(?<=0)1(?=0)", a)))

Prints:

3
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

It appears that a part of the string can not be used multiple times for different occurences in count().

"01010101"
 --- <-- occurence 1
     --- <-- occurence 2
Erik
  • 722
  • 4
  • 11
0

python str objects' count method as per the docs counts non-overlapping strings. So if you have "01010" "010" only occurs once because after it finds the first occurrence it scans from that point on and has only "10" which is not "010" here is a tutorial on counting overlapping strings: https://www.codespeedy.com/count-overlapping-substrings-in-a-given-string-in-python/

also see this question: String count with overlapping occurrences

David Oldford
  • 1,127
  • 4
  • 11