Python: Find string in a file and print which line it was found on [closed]

北城以北 提交于 2020-01-30 13:04:39

问题


I have been browsing stack overflow for ages now and could not find a solution to this. I need to find a string in a txt file, and then print which line that string was found on. Being the idiot I am, I could not figure this out myself, and I could not find an answer here. And thus, I need a snippet that can do this. I am using Python 2.7.


回答1:


In Python, enumerate is handy for this sort of thing:

with open(myfile) as f:
    for index, line in enumerate(f, 1):
        if s in line:
            print("'{0}' found on line {1}".format(s, index))


来源:https://stackoverflow.com/questions/21357132/python-find-string-in-a-file-and-print-which-line-it-was-found-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!