Python字符串比较提供了意外的输出

时间:2019-04-04 18:05:45

标签: python subprocess

我正在尝试比较两个变量:

node_latest_version-来自抓取 installed_version-通过执行node -v并将值存储在变量中。

在执行时显示相同的值:

print(node_latest_version)
# prints v11.13.0

print(installed_version)
# prints v11.13.0

但是当我尝试将两者进行比较

if node_latest_version == installed_version:
    print('success')
# No response

我尝试过:

if node_latest_version == 'v11.13.0':
   print('OK')
# this prints OK

if installed_version == 'v11.13.0':
   print('OK')
# NO RESPONSE

if type(node_latest_version) == str:
   print('OK')
# this prints OK

if type(installed_version) == str:
   print('OK')
# this prints OK

这是我的代码:

node_latest_version = results[1].attrs['data-version']

installed_version = subprocess.Popen("node -v",
                           shell=True,
                           stdout=subprocess.PIPE,
                           universal_newlines=True).communicate()[0]

print(node_latest_version)
print(installed_version)

if node_latest_version == installed_version:
   print('OK')

我希望比较两个值

2 个答案:

答案 0 :(得分:1)

在比较之前,在两个字符串上都使用.strip()方法。 installed.strip()== Latest.strip()

答案 1 :(得分:-1)

尝试一下并进行比较:

node_latest_version = ''.join(x for x in node_latest_version if x.isdigit() or x == '.')
installed_version = ''.join(x for x in installed_version if x.isdigit() or x == '.')

if node_latest_version == installed_version:
   print('OK')