python - 从文本文件中的行创建字符串列表的大多数 pythonic 方法?

标签 python string list text-files

<分区>

从一个文本文件lines_of_words.txt,说

first
second
third

必须创建一个单词列表作为字符串,即

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

完成这项工作最符合 Python 风格的函数是什么?到目前为止,我的出发点是

with open('list_of_words', 'r') as list_of_words:
    # Do something...
print(list_of_strings)

最佳答案

您只需在文件处理程序上使用 list(..) 即可。由于字符串将包含一个新行,您可能希望使用 str.rstrip 删除右侧的 '\n' 部分:

with open('list_of_words', 'r') as f:
    list_of_strings = <b>list(map(str.rstrip,</b> f<b>))</b>
print(list_of_strings)

关于python - 从文本文件中的行创建字符串列表的大多数 pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57135952/

相关文章:

python - 如何检查列表中的所有元素是否相同?

c++ - 使用函数更改 std::string 的内容

c++ - 带有 %s 和 std::string 的 sprintf 给出乱码

android - 我们可以在 values 文件夹中为 sting strings (Android) 创建 new_strings.xml 和 strings.xml 吗?

用于查找 "contains"的 Java 8 lambda 表达式

python - PyMySQL 返回字节而不是 str

python - 使用单个元素解压元组,如果元组为 None,则返回 None

确定空列表条目是否为 'continuous' 的 Pythonic 方法

python - 如何修复 python 3.7 中软件包安装 (fcm) 期间的 gcc 错误

python - 如何使用 set 维护列表的顺序?