python - '\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?
解决方案
要摆脱空白字符,您可以使用strip
:
wordList.append(line.strip().split(','))
此外,您的函数不会返回任何内容,因此在 python中也result = function("file1.txt","file2.txt")
不会分配任何内容。要让它返回一些东西,请在函数末尾使用:result
None
return
return wordlist
也可以返回多个变量:
return var1, var2, ...
你可以通过
a, b, ... = function(..)
推荐阅读
- react-native - VirtualizedLists 不应该嵌套在具有相同方向的普通 ScrollViews 中 - 改用另一个 VirtualizedList-backed 容器
- java - sbt compile play framework 应用错误
- jquery - jquery未处理的异常如何处理这个异常
- c++ - 我的 if 语句打印在我的 while 循环中的每个 if 语句上,无论它是否为假
- amazon-ec2 - 无法在资源 AWS::ECS::Service 上添加标签
- ajax - 通过 laravel 中的多选下拉列表过滤数据表
- ruby-on-rails - 使用omniauth-twitter 的Ruby on rails 应用程序无法在heroku 上运行“我们很抱歉,但出了点问题。”
- algorithm - 解决问题的方法 UVA 10461 差异
- flutter - 如何更改 Flutter gridview.count 复选框列表的状态?
- html - 导航栏周围的空白(仅限移动设备)