【问题标题】:problems removing newline character in python [duplicate]在python中删除换行符的问题[重复]
【发布时间】:2012-05-06 06:31:01
【问题描述】:

除了已经在代码中的那些之外,我还尝试使用 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")

【问题讨论】:

  • 只遍历文件有什么问题?
  • 在剥离调试之前尝试添加一个 print newString
  • 我有,脱衣前后没有区别,我觉得很奇怪
  • 尝试在 strip 前后打印 repr(newString),如果在 strip 之前没有显示 \n 则字符串永远不会有换行符
  • 两者都有新字符串。这是 fasta 文件的样子

标签: python newline


【解决方案1】:

字符串是不可变的:

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() 方法关闭文件。

【讨论】:

  • 编辑给出了一些建议。
  • 谢谢,我刚刚用分割线替换了条带。 PEP 8 的评论是否也参考了 newString 而不是 new_string 的命名?
  • @AlbertoDoes:这是一个一般建议:大多数用于变量命名,但也用于空格(例如运算符周围)或条件(if cond or cond2 优于 if(cond) or (cond2))。
  • 太好了,感谢您的建议。我没有意识到 splitline 方法在列表中添加了新内容。我通过使用 new_string = text[endIndex+1:].replace('\n', '') 找到了解决问题的方法
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2013-07-26
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多