【问题标题】:How to make the program tell you which line is being printed? [duplicate]如何让程序告诉你正在打印哪一行? [复制]
【发布时间】:2020-12-10 00:19:39
【问题描述】:

所以有这个非常简单的代码:

keywords = open('a.txt','r').read().splitlines()

for i in keywords:
    print(i)

它的作用是从 txt 文件中打印出每一行

所以让我们说在那个 txt 文件中有一个列表:

dog
eat
sleep

并且这段代码基本上会打印出该 txt 文件中的每一行,但问题是,我想修改代码,以便程序也能够判断当前正在打印出哪一行,所以就像输出如下所示:

dog 1
eat 2
sleep 3

我该怎么做?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:
    with open('a.txt', 'r') as f:
        data = f.readlines()
        for index, line in enumerate(data, 1):
            print("{} {}".format(line.strip(), index))
    

    【讨论】:

    • 请提供一些信息,而不是仅仅抛出一些代码;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2011-02-21
    • 2021-11-19
    • 2014-06-06
    相关资源
    最近更新 更多