当我在代码下面运行时,为什么会出现“无效语法”。 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")
答案 0 :(得分:5)
在行中:
def countSubStringMatch("atgacatgcacaagtatgcat","atgc")
您应该删除def
。定义函数时使用def
,而不是在调用函数时使用。{/ p>
答案 1 :(得分:3)
您的代码出现其他问题:
您不在字符串模块中使用也不需要任何内容。不要从中导入。
除非你有充分的理由,否则不要from somemodule import *
。
第一次find
返回-1后,你的代码相当缓慢而毫无意义地挣扎......你的循环应该包括
if fsi == -1: return counter
以便您立即返回正确的计数。
保持一致:您使用counter += 1
但fsi = fsi + 1
...这让我想起:在www.python.org找到'PEP 8'(风格指南)并阅读 - 你的空格键必须感觉不受欢迎; - )
HTH
约翰
答案 2 :(得分:3)
你可以做的字符串计数:
target = "atgacatgcacaagtatgcat"
s = 'atgc'
print '%s is %d times in the target string' % (s, target.count(s))