Goutham Pathuri Goutham Pathuri - 7 months ago 28
Python Question

Elif Condition in Python

I have some Python code which needs to take a string input from a text file named

varfile.txt
and conditions to be applied on that data and print the output. The code is as follows:

file = open("varfile.txt", "r")
lines = file.readlines()
e= str(lines[1]);
print(e)
if e == '<0.1%':
print("1")
elif e == '(0.1-25)%':
print("2")
elif e == '(0.25-0.5)%':
print("3")
elif e == '(0.5-1)%':
print("4")
elif e == '>1%':
print("5")
else:
print("0")


The ouput is as follows:

(0.25-0.5)%
0


Even though
e
value is printed as
(0.25-0.5)%
, it is not comparing with the condition in the elif clause and giving
0
as an output though the output should be
3
. Could you please suggest where I am going wrong?

Answer

According to this tutorial files.readlines() does not strip the ending new line characters from the ends of the lines.

You can use e.strip('\n') to return a string with newlines removed, e.g.:

e = e.strip('\n')
if e == ...:
elif ...