-3

My if statement looks weird, but I can't think of how I prevent of -1 value from printing :

### script counts the number of times that a key string appears in target string 

from string import *

def countSubStringMatch(target,key):
    value = target.find(key, 0)
    print value

    while value > -1:
        value = value + 1
        value = target.find(key, value)

        if value != -1:
            print value
        else:
            break

countSubStringMatch("atgacatgcacaagtatgcat","atg")

This is my output:

0
5
15
scsi
  • 13
  • 3
  • You're method is almost certainly not the best way of tackling this problem. But I think you should replace the print within the function definition with a return. Could you show the output of the function you call in an edit? – draco_alpine Jul 19 '16 at 20:13

3 Answers3

2

You can remove the initial print statement, and instead print the value at the beginning of the body of your loop, rather than at the end.

def countSubStringMatch(target,key):
    value = target.find(key, 0)

    while value > -1:
        print value

        value = value + 1
        value = target.find(key, value)

By the way, if you just want the number of matches and not the index of the start of each match, you can use count:

>>> count("atgacatgcacaagtatgcat","atg")
# 3
Greg
  • 597
  • 1
  • 6
  • 16
2

Please use as much as possible the code, other people have already written. Based on Find all occurrences of a substring in Python:

string = "atgacatgcacaagtatgcat"
print [i for i in range(len(string)) if string.startswith('atg', i)]
Community
  • 1
  • 1
Ohumeronen
  • 1,769
  • 2
  • 14
  • 28
1
def countSubStringMatch(target,key):
   res = set( [ data.find('atg',i) for i in range(len(data)) ] )
   res.remove(-1)
   print res

countSubStringMatch("atgacatgcacaagtatgcat","atg")

set([0, 5, 15])
galaxyan
  • 5,944
  • 2
  • 19
  • 43