0

除了代码中已有的之外,我还尝试使用 newString.strip('\n') ,但它没有做任何事情。我正在输入一个不应该有问题的 .fasta 文件。提前致谢。

def createLists(fil3):
    f = open(fil3, "r")
    text = f.read()

    listOfSpecies = []
    listOfSequences = []

    i = 0
    check = 0

    while (check != -1):
        startIndex = text.find(">",i)
        endIndex = text.find("\n",i)
        listOfSpecies.append(text[startIndex+1:endIndex])

        if(text.find(">",endIndex) != -1):
            i = text.find(">",endIndex)
            newString = text[endIndex+1: i]
            newString.strip()
            newString.splitlines()
            listOfSequences.append(newString)

        else:
            newString = text[endIndex+1:]
            newString.strip()
            newString.strip('\n')
            listOfSequences.append(newString)
            return (listOfSpecies,listOfSequences)


def cluster(fil3):
    print createLists(fil3)


cluster("ProteinSequencesAligned.fasta")
4

2 回答 2

4

字符串是不可变的:

In [1]: s = 'lala\n'

In [2]: s.strip()
Out[2]: 'lala'

In [3]: s
Out[3]: 'lala\n'

In [4]: s = s.strip()

In [5]: s
Out[5]: 'lala'

所以就这样做:

new_string = text[end_index+1:].strip()

请遵循 PEP 8。此外,您可以只在行上使用 for 循环来重写循环。Python 文件支持直接迭代:

In [6]: with open('download.py') as fobj:
   ...:     for line in fobj:
   ...:         print line

如果您不使用该with语句,请确保使用close()函数末尾的方法关闭文件。

于 2012-05-06T07:00:32.840 回答
0

那么最后我发现最好的解决方案是 new_string = text[endIndex+1:].replace('\n', '')

于 2012-05-06T16:56:21.523 回答