且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python-从文本文件中查找行号

更新时间:2023-02-26 20:47:51

with open('test.txt') as f:
    content = f.readlines()

index = [x for x in range(len(content)) if 'pizza' in content[x].lower()]

代码的第(1)部分将每一行作为变量"content"中的单独列表读取.

Part (1) of the code reads each line as a separate list in variable "content".

只有在该行中存在"pizza"的情况下,第(2)部分才会填充内容的行号. [x代表range(len(content()))中的x]仅填充所有索引值,而如果content [x] .lower()中的'pizza"则保持与字符串匹配的行号.

Part (2) populates out the line # of content only if 'pizza' exists in that line. [x for x in range(len(content))] simply populates all index values, while 'if 'pizza' in content[x].lower()' keeps the line # that matches the string.