Reputation: 23
I want the block of code under the if-statement to only run if the word "trip" is found in that particular line. However, my print output indicates that even the lines without the word "trip" are in the result. This is the code:
for line in file:
#match = re.search(r'\rTrip', line)
#if match:
if line.find('\rTrip') != -1:
someArray = []
times = re.compile(r'\d+:\d+')
miles = re.compile(r'\d+\.\d+')
names = re.compile(r'[A-Za-z]{2,25}||\s[A-Za-z]{2,25}')
nam = line.split('\rTrip')
num = line.split()
drivenTimes = times.findall(str(num))
drivenMiles = miles.findall(str(num))
driverNames = names.findall(str(nam))
someArray.append(line)
print(line)
Upvotes: 0
Views: 69
Reputation:
See correct code here !!!
import re
with open('C:\\Users\\Grace\\Documents\\test.txt', 'r') as lines:
line2=lines.read().split('\n')
for line in line2:
if line.find('Trip') == -1:
someArray = []
times = re.compile(r'\d+:\d+')
miles = re.compile(r'\d+\.\d+')
names = re.compile(r'[A-Za-z]{2,25}||\s[A-Za-z]{2,25}')
nam = line.split('\rTrip')
num = line.split()
drivenTimes = times.findall(str(num))
drivenMiles = miles.findall(str(num))
driverNames = names.findall(str(nam))
someArray.append(line)
print(line)
Upvotes: 0
Reputation: 48028
Substring matching in python can be accomplished using the in
operator. IE:
if 'trip' in line:
# Code here for the presence of "trip"
Upvotes: 2