0

Here is a code I wrote to check for the number of occurrence of a sub_string within a string:

a = 'ABCDCD' #Main String
b = 'CDC'    #Sub String

sub_Len = len(b)
occurrence = 0

for s in range(len(a)):
    if a[s:s+sub_Len] == b:
        occurrence += 1 
dspysql
  • 3
  • 1
  • 4
    Why would you want to use a list comprehension, which is for *creating lists*, you aren't doing that here – juanpa.arrivillaga Feb 06 '20 at 20:43
  • I wanted to see if there was a faster way of doing it. When I timed the original code and list comprehension on jupyter notebook, the original code was faster. – dspysql Feb 06 '20 at 20:59
  • If it's speed you're after, here's a duplicate with a lot of different methods you can test: https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences – tzaman Feb 06 '20 at 21:02
  • _When I timed the original code and list comprehension on jupyter notebook_ - do you already have the list comprehension? – Harshal Parekh Feb 06 '20 at 21:07
  • **maverick** answered my question, I have marked it as the correct one. – dspysql Feb 06 '20 at 21:17

3 Answers3

2

This isn't a list comprehension, but it is shorter for your code:

a.count(b)

Docs

schillingt
  • 13,493
  • 2
  • 32
  • 34
1

While list comprehension is not needed here, you can reduce your code to one line using list comprehension to count the number of occurrences of your substring

print(sum([1 for s in range(len(a)-len(b)+1) if a[s:s+len(b)] == b]))

Here list comprehension creates a list of 1's for every occurrence of the substring, and then sum() is used to add the count

maverick
  • 150
  • 1
  • 2
  • 10
1

Here's one way:

sum(1 for i in range(len(a)) if a.startswith(b, i))
  • We use startswith with a start index to avoid slicing the string.
  • Technically this is a generator expression, which avoids creating an intermediate list before feeding it to sum.
tzaman
  • 46,925
  • 11
  • 90
  • 115