删除python中换行符的问题

2024-03-28 09:27:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我也试过用新闻字符串.string.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")

Tags: textdefcheckfindfastastripclusterappend
2条回答

字符串是不可变的:

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'

所以就这么做吧:

^{pr2}$

请遵循政治公众人物8。 此外,您可以在行上使用for循环重写循环。Python文件支持直接迭代:

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

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

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

相关问题 更多 >