首页 > 解决方案 > 检查字符串是否为大于 1 的数字

问题描述

我正在尝试检查字符串是否为大于 1 的数字。字符串格式为 Minutes:Seconds = 0:12

这是我的方法,但有时我会收到此错误“列表索引超出范围”

length = driver.find_element_by_xpath("/html/body/path[2]").text
# length output would be something like 0:28
x = list(length)
    if int(x[0]) < 1:
       print("Less than 1 minute.")
    else:
       pass

我怎样才能更有效地完成这项任务并避免出现“列表索引超出范围”错误

标签: pythonselenium-chromedriver

解决方案


如果length总是:介于分钟和秒之间,您可以使用字符串split函数将其转换为列表。但是,如果您收到“列表索引超出范围错误”,您可能需要检查它length是否具有您期望的格式。

x = length.split(":")
if int(x[0]) < 1:
    print("Less than 1 minute.")
else:
    pass

推荐阅读