字符串比较失败 [英] String comparison fails
本文介绍了字符串比较失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
output = subprocess.check_output("./mount.sh", shell=True)
print output
if output == "expected_String":
print "Hurray!"
(打印命令只是检查输出是否符合我的预期)。每次比较都会失败我不明白为什么。我用这个代替了check_output
(The print command is just to check if the output is what I expected).The comparison fails everytime and I don't get why. I tried it with this instead of check_output
(stdout, stderr) = Popen(["./mount.sh"], stdout=PIPE).communicate()
mountout = stdout
但我不认为这是这里的问题,因为
but I don't think that's the problem here because
print output
给出了我的期望,但是如果我尝试将其与我的 expected_String进行比较,它总是错误的。
gives me what I expect but if I try to compare it to my "expected_String" it is always false.
推荐答案
我相信问题在于您的输出末尾包含其他换行符。您可以通过调用 .strip()
来删除它们:
I believe the problem is your output contains additional new line character at the end. You can fix it by calling .strip()
to remove those:
output = subprocess.check_output("./mount.sh", shell=True)
output = output.strip()
更新:如何查找字符串是否以换行符结尾?
请考虑以下交互式会话:
Update: How to Find out If a String Ends with New Line?
Consider the following interactive session:
>>> s = '''hello\n'''
>>> s.endswith('\n')
True
这篇关于字符串比较失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文