在if语句中在错误条件下执行的python代码

时间:2018-10-01 20:59:47

标签: python string if-statement

我希望if语句下的代码块仅在该特定行中找到单词“ trip”时才运行。但是,我的打印输出表明即使结果中没有单词“ trip”的行也是如此。这是代码:

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)

2 个答案:

答案 0 :(得分:2)

可以使用in运算符来完成python中的子字符串匹配。 IE:

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

答案 1 :(得分:0)

在此处查看正确的代码!!!

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)