2010-08-19 51 views
-3

为什么我在代码下运行时遇到“无效语法”。 Python 2.7版python目标字符串键值无效语法

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") 
+0

请修复代码格式,使用小'101/010'按钮 – 2010-08-19 20:36:44

+2

-1我认为在SO上提出问题的最低标准应该是提问者理解语言的语法,* eg *使用'def'关键字。 – 2010-08-20 06:02:04

回答

5

在行:

def countSubStringMatch("atgacatgcacaagtatgcat","atgc") 

您应该删除def。定义一个函数时使用def,而不是在调用它时使用。

+0

对于问这样一个简单的问题,初学者的错误表示歉意......谢谢 – raoulbia 2010-08-26 23:13:46

3

其他的事情你的代码错误:

  1. 你不使用,不需要串模块中的任何东西。不要从它导入。

  2. 不要做from somemodule import *除非你有很好的理由。

  3. 您的代码后的第一次缓慢而无谓的斗争上find返回-1 ...你的循环应该包括

    if fsi == -1: return counter

    ,让你用正确的计数立即返回。

  4. 是一致的:你用counter += 1fsi = fsi + 1

  5. ......这让我想起:找到 'PEP 8'(风格指南)在www.python.org,阅读它 - 你的空格键必须被不被爱的感觉;-)

HTH
约翰

+0

嗨,John,感谢您向我提出这个问题! – raoulbia 2010-08-21 21:32:35

+0

@Baba:(1)看我的编辑;在问题#3中,应该返回'counter',而不是'0'(2)问题#6:计算'len(dna)'ONCE,在进入'while'循环之前 – 2010-08-21 21:55:19

3

字符串算你可能只是这样做:

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