【问题标题】:'\n' and 'None' appearing at end of console outputted List. How to remove them?'\n' 和 'None' 出现在控制台输出列表的末尾。如何删除它们?
【发布时间】:2018-11-11 02:56:58
【问题描述】:

我是 Python 文件的新手,在我的输出控制台中删除 '\n' 和单词 None 时遇到问题。这是我的代码:

def function(inputFile, wordFile):
    input = open(inputFile, 'r')
    words = open(wordFile, 'r')

    wordList = []

    for line in words:
        wordList.append(line.split(','))

    print(wordList)
    words.close()

##call function
result = function("file1.txt","file2.txt")
print(result)
print()

我的 file2.txt/wordFile/words 看起来像这样:

你好,世界

123,456

这是我得到的输出:

['你好','世界\n']

['123', '456\n']

我知道发生了很多事情,但是如何删除 '\n' 和 None

【问题讨论】:

  • function 应该返回 wordList,而不是打印它。关于\n,例如str.strip
  • return 确实删除了“无”部分,谢谢!但是 str.strip 不能在 Lists 上工作吗?
  • 在拆分之前必须将其应用到字符串。
  • 编写代码的好方法是:with open(wordFile) as words: return [line.rstrip().split(',') for line in words]。因此,整个函数将是单行的。

标签: python list function file


【解决方案1】:

要去除空白字符,您可以使用strip

wordList.append(line.strip().split(','))

此外,您的函数不会返回任何内容,因此result = function("file1.txt","file2.txt") 会将 nothing 分配给result,在 python 中也称为None。要让它返回一些东西,请在函数末尾使用return

return wordlist

也可以返回多个变量:

return var1, var2, ...

你可以通过

a, b, ... = function(..)

【讨论】:

  • 只是需要其他答案。我刚刚意识到这个解决方案的问题是,一旦我“返回单词表”,我就无法为“函数”的其余部分返回任何其他内容。有什么方法可以在不使用 return 或使用两个函数的情况下完成这项工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-30
  • 2017-11-15
  • 2011-05-15
  • 2014-02-15
  • 2011-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多