0

I want to count a long string contain how many substring, how to do it in python?

"12212"

contains 2x "12"

how to get the count number?

It must allow for overlaping substrings; for instance "1111" contains 3 "11" substrings.

"12121" contains 2 "121" substrings.

"1111".count("11")

will return 2. It does not count any overlaps.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user504909
  • 9,119
  • 12
  • 60
  • 109
  • http://stackoverflow.com/a/1155647/16139 – ksuralta Aug 11 '14 at 14:55
  • The important question is how you want to handle overlapping matches: `"121212".count("1212") == 1`, which might not be what you want. – DSM Aug 11 '14 at 14:58
  • 2
    In case you want to count overlapping substrings, you could use this: `count_all = lambda string, sub: sum(string[i:i+len(sub)] == sub for i in range(len(string) - len(sub) + 1))` – tobias_k Aug 11 '14 at 15:05
  • @Martijn Sorry, but I add some more detail information about can contain overlap and repeat. – user504909 Aug 11 '14 at 15:12
  • Now it is a duplicate of [string count with overlapping occurances](http://stackoverflow.com/q/2970520) – Martijn Pieters Aug 11 '14 at 15:18
  • possible duplicate of [string count with overlapping occurances](http://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurances) – DSM Aug 11 '14 at 15:20

1 Answers1

3

Strings have a method count

You can do

s = '12212'

s.count('12') # this equals 2

Edited for the changing question, the answer below was posted as a comment by tobias_k

To count with overlap,

count_all = lambda string, sub: sum(string[i:i+len(sub)] == sub for i in range(len(string) - len(sub) + 1))

This can be called with,

count_all('1111', '11') # this returns 3
Lfa
  • 1,069
  • 2
  • 10
  • 23