检查字符串是否为大于 1 的数字

Check if a string is a number greater than 1

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

这是我的方法,但有时我会收到此错误 'list index out of range'

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

我怎样才能更有效地完成这项任务并避免出现 'list index out of range' 错误

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

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

请记住,您将来可能还需要考虑时间。最好的解决方案是使用内置的 'time' 模块。

from datetime import datetime

datetime_str = '13:55:26'

datetime_object = datetime.strptime(datetime_str, '%H:%M:%S')

datetime.datetime(1900, 1, 1, 13, 55, 26) # Now everything you need is easily accessible 

datetime_object.minute # 55
datetime_object.second # 26

https://docs.python.org/3/library/time.html