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?
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, eg:
e = e.strip('\n')
if e == ...:
elif ...
readlines
包含换行符 。
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.