简体   繁体   English

Python中的Elif条件

[英]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. 我有一些Python代码,需要从名为varfile.txt的文本文件中获取字符串输入,以及要应用于该数据的条件并打印输出。 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 . 即使e值打印为(0.25-0.5)% ,它也不会与elif子句中的条件进行比较,尽管输出应为3但它的输出为0 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. 根据本教程, files.readlines()不会从行尾files.readlines()结尾的换行符。

You can use e.strip('\\n') to return a string with newlines removed, eg: 您可以使用e.strip('\\n')返回删除了换行符的字符串,例如:

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

readlines 包含换行符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM