python目标字符串键计数无效语法
为什么当我运行下面的代码时会得到一个“无效语法”。Python 2.7python目标字符串键计数无效语法,python,string,syntax,Python,String,Syntax,为什么当我运行下面的代码时会得到一个“无效语法”。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
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")
从字符串导入*
def countSubStringMatch(目标,键):
计数器=0
fsi=0#fsi=查找字符串索引
而fsi在该行中:
def countSubStringMatch("atgacatgcacaagtatgcat","atgc")
您应该删除def
def
在定义函数时使用,而不是在调用函数时使用。代码中的其他错误:
字符串模块中不使用也不需要任何内容。不要从中导入
不要从somemodule导入中执行*
,除非你有很好的理由
当find
第一次返回-1时,您的代码会缓慢而毫无意义地继续运行。。。你的循环应该包括
如果fsi==-1:返回计数器
以便您立即返回正确的计数
保持一致:使用计数器+=1
但fsi=fsi+1
。。。这提醒了我:在www.python.org上找到“pep8”(风格指南),并阅读它——你的空格键一定感觉不被爱;-)
HTH
John对于字符串计数,您可以执行以下操作:
target = "atgacatgcacaagtatgcat"
s = 'atgc'
print '%s is %d times in the target string' % (s, target.count(s))
请修改代码格式,使用小的101/010
按钮-1我认为提问的最低标准应该是询问者理解语言的语法,例如使用def
关键字。@Baba:(1)请参阅我的编辑;在问题#3中,应该返回计数器
,而不是0
(2)问题#6:在输入之前计算len(dna)
一次,而循环为问这么简单的问题道歉,初学者的错误…谢谢