简体   繁体   中英

Code under if-statement performing under false conditions in python

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)

Substring matching in python can be accomplished using the in operator. IE:

if 'trip' in line:
  # Code here for the presence of "trip"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM