检测字符串是否在另一个字符串中

时间:2013-02-28 12:48:36

标签: python python-3.x

我正在尝试检测软件版本是否是最新的,我正在使用Python 3.3中的以下代码执行此操作:

if str(version) in str(buildno):
    print("Your software version is up to date. \n")
else:
    print("Your software is out of date. Updating your software. \n")

但是,即使它是最新的,它也会不断更新软件。我也尝试了代码变体:

if str(version) in str(buildno) == True:
    print("Your software version is up to date. \n")
else:
    print("Your software is out of date. Updating your software. \n")
    if os == "Windows":
        subprocess.call("windowsUpgrade.sh", shell=True)

这也行不通。我使用的方法是可行的还是我应该采取另一种方法来解决这个问题?

>>> print(version)
4.3.0-18107
>>> print(buildno)
('4.3.0-18107', 1)

感谢您提供的任何答案。

4 个答案:

答案 0 :(得分:1)

您的第二个变体不起作用。如果您交换buildnoversion

,第一个版本应该有效
buildno = '4.3.0-18107'
version = ('4.3.0-18107', 1)

if str(buildno) in str(version):
    print("Your software version is up to date. \n")

我假设一个是字符串而另一个是元组,但它们可以是任何东西,因为我们只看到它们打印而不是你如何得到它们。

从它们的内容来看,这些变量名称有些误导,交换或不交换。

答案 1 :(得分:1)

您的buildno是一个元组。您只需要第一个项目。那就是:

if str(buildno[0]) in str(version):

甚至:

if str(buildno[0]) == str(version):
正如Pavel Anossov在评论中所说的那样。

另一方面,您的第二种方法是:

if str(buildno) in str(version) == True:

可以使用dis粗略翻译为:

if str(buildno) in str(version) and str(version) == True:

另外,请查看DSM对您问题的评论。

  

使用这样的字符串包含会导致麻烦:'4.3.0-1'在'4.3.0-11'中,但可能不是最新的。根据您的版本编号策略,您可能需要创建一个int元组来进行比较。

答案 2 :(得分:1)

好像这里使用的数据类型存在混淆

Tuple to String:

str(('4.3.0-18107', 1)) = "('4.3.0-18107', 1)"

元组不在字符串中:

if "('4.3.0-18107', 1)" in '4.3.0-18107' # False

元组中的字符串

if '4.3.0-18107' in "('4.3.0-18107', 1)" # True 

String in(first index Tuple = String)

if '4.3.0-18107' in ('4.3.0-18107', 1)[0] # True

如果顺序无关紧要,则需要在转换为字符串之前索引元组str(('4.3.0-18107',1)[0])。您在上面的代码中所做的是将元组转换为字符串而不是版本。因此,帕维尔·阿诺索夫是正确的,交换应该在这里起作用 - 至少它是为我做的。

所以这最终奏效了(错过了一个空白):

buildno=buildno[0] 
version=str(version.strip()) 
buildno=str(buildno.strip()) 
if version == buildno

或更短:

if str(version).strip() == str(buildno[0]).strip():
if str(version).strip() in str(buildno[0]).strip():

答案 3 :(得分:1)

由于您使用的是Python 3,因此可以使用PEP386中描述的distutils.version比较模块:

from distutils.version import LooseVersion as V

minimum_version = V(version)
current_version = V(buildno)

if current_version >= minimum_version:
    print("Your software version is up to date. \n")
else:
    print("Your software is out of date. Updating your software. \n")

还有一个StrictVersion类,但它似乎不适用于您的版本编号。

相关问题