简体   繁体   中英

If in for-loop not working even though the condition is satisfied

Running the following code to compare values in a column of a text file to a given number, in this case 440

with open('test.txt', 'a+') as input:
 for line in input:
  columns = line.split(" ")
  print columns[5] #test
  if columns[5] == '440':
   print 'match'

test.txt is just:

0 0 0 0 0 1
0 0 0 0 0 440
0 0 0 0 0 1   
0 0 0 0 0 440
0 0 0 0 0 1
0 0 0 0 0 1

The print columns[5] bit prints out the right value from the txt file, but even when it matches 440, the if inside the for-loop doesnt work

thank you for any help

Since your 440 is the last thing on the line, column[5] == '440\\n'

You need to strip the values before comparing.

if columns[5].strip() == '440':

or strip it first:

columns = line.strip().split(" ")

or use the general split, which will split on all whitespace:

columns = line.split()

Or do an actual number comparison

if int(columns[5]) == 440:

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