2010-08-19 48 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))