【问题标题】:python target string key count invalid syntaxpython目标字符串键计数无效语法
【发布时间】:2010-08-19 20:32:25
【问题描述】:

为什么我在以下代码下运行时会收到“无效语法”。 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")

【问题讨论】:

  • 请修正代码格式,使用小101/010按钮
  • -1 我认为就 SO 提问的最低标准应该是提问者理解语言的语法,例如使用def 关键字。跨度>

标签: python string syntax


【解决方案1】:

行内:

def countSubStringMatch("atgacatgcacaagtatgcat","atgc")

您应该删除defdef 在定义函数时使用,而不是在调用时使用。

【讨论】:

  • 抱歉问了这么简单的问题,初学者的错误...谢谢
【解决方案2】:

对于字符串计数,您可以这样做:

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

【讨论】:

    【解决方案3】:

    您的代码有其他问题:

    1. 在字符串模块中你不使用也不需要任何东西。不要从中导入。

    2. 除非你有充分的理由,否则不要使用from somemodule import *

    3. find 第一次返回 -1 之后,您的代码相当缓慢且毫无意义地挣扎……您的循环应该包括

      if fsi == -1: return counter

      以便您立即返回正确的计数。

    4. 保持一致:你使用counter += 1,但fsi = fsi + 1

    5. ...这提醒了我:在 www.python.org 找到“PEP 8”(样式指南)并阅读它——你的空格键一定感觉不受欢迎;-)

      李>

    HTH
    约翰

    【讨论】:

    • @Baba:(1)查看我的编辑;在问题#3 中,应该返回counter,而不是0 (2) 问题#6:计算len(dna) ONCE,然后进入while 循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2022-11-20
    相关资源
    最近更新 更多