【问题标题】:Python: using .split() on an external text filePython:在外部文本文件上使用 .split()
【发布时间】:2021-12-01 01:56:50
【问题描述】:
with open('books2.txt', 'rt') as f:
    data = f.readlines()
for line in data:
    if 'Fiction' in line:
        line.split(' ,')
        print(line)

以上是我当前的代码,输出如下

The Great Gatsby, Fiction, Fitz Gerald,11/11/2021,0

我如何能够通过逗号分割每一行并将每个分割打印到一个新行上?:

The Great Gatsby
Fiction
Fitz Gerald
etc

【问题讨论】:

  • 替换不拆分? print(line.replace(', ', '\n')) 但是会有逗号的标题吗?也许使用 csv 解析器。

标签: python split


【解决方案1】:

用“,”分割,然后从分割中删除空格。用“\n”加入他们。

print("\n".join([ s.strip() for s in string.split(",")]))

输出:

The Great Gatsby
Fiction
Fitz Gerald
11/11/2021
0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多