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

标签 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)

感谢您提供的任何答案。

最佳答案

好吧,这里使用的数据类型似乎有些困惑

元组到字符串:

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]) 建立索引。您在上面的代码中所做的是将元组转换为字符串而不是版本。因此,帕维尔·阿诺索夫 (Pavel Anossov) 认为交换应该在这里起作用是正确的 - 至少它对我有用。

所以这最终奏效了(遗漏了一个空格):

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():

关于python - 检测一个字符串是否在另一个字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15135962/

相关文章:

python - Python中分组数据的累积自定义函数

javascript - 使用转换后的 JS 函数在 Python 中进行反混淆

python - 将递归函数转换为for循环和while循环

python - 如何使用 cv2.kmeans 中的标签作为列表的索引?

python - 如何将 2 列常量添加到指定位置的列表中?

python - 使用许多多项式的梯度下降不收敛

javascript - 使用 selenium 将图像从浏览器内存复制到 python 内存

python - 如何查询SQLAlchemy中的关联表?

python - 如何按 3 列打印 2 本词典

python - 如何创建一个 numpy 数组,其元素是其他 numpy 数组对象?