首页 > 解决方案 > '\n' 和 'None' 出现在控制台输出列表的末尾。如何删除它们?

问题描述

我是 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

标签: pythonlistfunctionfile

解决方案


要摆脱空白字符,您可以使用strip

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

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

return wordlist

也可以返回多个变量:

return var1, var2, ...

你可以通过

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

推荐阅读