字符串比较失败

use*_*061 2 python string comparison

output = subprocess.check_output("./mount.sh", shell=True)
print output
if output == "expected_String":
      print "Hurray!"
Run Code Online (Sandbox Code Playgroud)

(打印命令只是为了检查输出是否符合我的预期)。每次比较都失败,我不明白为什么。我用这个而不是 check_output 试过了

(stdout, stderr) = Popen(["./mount.sh"], stdout=PIPE).communicate()
mountout = stdout
Run Code Online (Sandbox Code Playgroud)

但我不认为这是这里的问题,因为

 print output
Run Code Online (Sandbox Code Playgroud)

给了我我的期望,但如果我尝试将它与我的“expected_String”进行比较,它总是错误的。

Hai*_* Vu 5

我相信问题是您的输出在末尾包含额外的换行符。您可以通过调用.strip()删除这些来修复它:

output = subprocess.check_output("./mount.sh", shell=True)
output = output.strip()
Run Code Online (Sandbox Code Playgroud)

更新:如何确定字符串是否以换行符结尾?

考虑以下交互式会话:

>>> s = '''hello\n'''
>>> s.endswith('\n')
True
Run Code Online (Sandbox Code Playgroud)