【发布时间】:2019-11-29 20:02:43
【问题描述】:
从文本文件lines_of_words.txt 说
第一
第二
第三个
必须创建一个字符串形式的单词列表,即
list_of_strings = ['first', 'second', 'third']
这似乎是一个极其微不足道的功能,但我找不到简洁的解决方案。我的尝试要么太麻烦要么产生错误的输出,例如
['f', 'i', 'r', 's', 't', '\n', 's', 'e', 'c', 'o', 'n', 'd', '\n', 't', 'h', 'i', 'r', 'd', '\n']
或
first
second
third
完成这项工作的最 Pythonic 函数是什么?到目前为止,我的出发点是
with open('list_of_words', 'r') as list_of_words:
# Do something...
print(list_of_strings)
【问题讨论】:
-
list_of_strings = list_of_words.readlines()。要去除换行符\n,请使用list(map(str.strip, list_of_words.readlines())) -
@abdusco:这将在每行末尾包含
'\n'字符。 -
最pythonic的方法是不将整个文件读入列表,而是逐行处理文件。
标签: python string list text-files