如何使用python在文件中找到确切的长度和匹配的字符串

时间:2012-10-03 09:19:05

标签: python

我有文件包含

"Starting program and 
Starting program
Loading molecule...
Initialising variables...
Starting the calculation - this could take a while!
Molecule energy = 2432.6 kcal mol-1
Calculation finished. Bye!"
import sys
import re

search_string = "Starting program"
txtlength=len(search_string)
print "txtlength",txtlength
lines = open( "C:\search.txt", "r" ).readlines()
for line in lines:
    if re.search( search_string, line ):
        print line,

    else :
        print "Not found"

我在文件中只找到第二行,但是来自此代码的输出是1行也显示

1 个答案:

答案 0 :(得分:0)

您显示的示例不需要正则表达式:

with open("C:/search.txt") as inp:
    for line in inp:
        if line.strip() == search_string:
            print line