1

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?

4
  • PLS upload the input file Commented May 4, 2016 at 7:57
  • I think you are using an extra space on the elif condition. It should be e == '(0.25-0.5)%' not ' (0.25-0.5)%' Commented May 4, 2016 at 7:58
  • ya..that is fine, you can see that it is printing the right value but there is some error in comparison Commented May 4, 2016 at 7:58
  • 1
    Generally, each line ends in a newline character, so you should be testing for e=='(0.25-0.5)%\n'. Commented May 4, 2016 at 8:01

2 Answers 2

7

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 ...
Sign up to request clarification or add additional context in comments.

1 Comment

I would recommend stripping all whitespace characters instead of only newlines before comparing, because files that users might change can easily contain spaces in the end of a line, which would else result in a hardly understandable error. So simply use e.strip().
1

readlines includes the newline character.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.