【发布时间】: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]。因此,整个函数将是单行的。