这个问题是关于如何找到特定文本(例如“这是我的马”)存在的行号?
文本文件:
this is my name
this is my address
this is my age
this is my horse
this is my book
this is my pc
我的代码:
with open ('test.txt', 'r') as infile:
?????
这个问题是关于如何找到特定文本(例如“这是我的马”)存在的行号?
文本文件:
this is my name
this is my address
this is my age
this is my horse
this is my book
this is my pc
我的代码:
with open ('test.txt', 'r') as infile:
?????
使用enumerate函数,因为它适用于可迭代的任何内容(您的文件是)。
for line_number, line in enumerate(infile):
print line_number, line
s = "this is my horse"
with open ('test.txt', 'r') as infile:
print next(index for index, line in enumerate(infile, start=1) if line.strip() == s)
打印4
。
请注意,您需要在行上应用strip()
才能在最后摆脱换行符。
你可以这样做:
with open ('test.txt', 'r') as infile:
data = infile.readlines()
for line, content in enumerate(data, start=1):
if content.strip() == 'this is my horse':
print line
如果您的文件将打印:
4