开发者

python target string key count invalid syntax

开发者 https://www.devze.com 2023-01-12 02:50 出处:网络
Why am i getting an \"invalid syntax\" when i run below code. Python 2.7 from string import * def countSubStringMatch(target,key):

Why am i getting an "invalid syntax" when i run below code. Python 2.7

from string import *

def countSubStringMatch(target,key):
    counter=0
    fsi=0 #fsi=find string index
    while fsi<len(target):
        fsi=dna.find(key,fsi)      
        if fsi!=-1:
           counter+=1
        else:
 开发者_开发问答           counter=0
            fsi=fsi+1
        fsi=fsi+1
    #print '%s is %d times in the target string' %(key,counter)

def countSubStringMatch("atgacatgcacaagtatgcat","atgc")


In the line:

def countSubStringMatch("atgacatgcacaagtatgcat","atgc")

You should remove the def. def is used when defining a function, not when calling it.


for string count you could just do:

target = "atgacatgcacaagtatgcat"
s = 'atgc'
print '%s is %d times in the target string' % (s, target.count(s))


Other things wrong with your code:

  1. You don't use and don't need anything in the string module. Don't import from it.

  2. Don't do from somemodule import * unless you have a very good reason for it.

  3. Your code rather slowly and pointlessly struggles on after the first time that find returns -1 ... your loop should include

    if fsi == -1: return counter

    so that you return immediately with the correct count.

  4. Be consistent: you use counter += 1 but fsi = fsi + 1

  5. ... which reminds me: find 'PEP 8' (style guide) at www.python.org, and read it -- your space bar must be feeling unloved ;-)

HTH
John

0

精彩评论

暂无评论...
验证码 换一张
取 消