【问题标题】:Comparing Ints concatenated from Strings in Python比较从 Python 中的字符串连接的整数
【发布时间】:2019-09-14 10:03:35
【问题描述】:

所以我正在尝试使用 Python 编写一个程序,该程序将在一定时间后发送文本提醒。我正在尝试检查时间是否在现实范围内(即一天不超过或少于 24 小时),但在尝试比较它们时出现错误。我无法比较从字符串连接的整数。

dur = input("How long do you want to wait (EX: HHMMSS): ")
hours = int(dur[0:1])
minutes = int(dur[2:3])
seconds = int(dur[4:5])
print(hours)
print(minutes)
print(seconds)

for n in range(0, LOOP):
    if(count == 0):
        # Check if hours is realistic
        if(hours > 0 and hours < 24 and str(hours[0]) == 0):
            hours = hours[1]
            count += 1

我收到一个 TypeError 说 > 在 str 和 int 的实例之间不支持。由于我无法将它们与>或

【问题讨论】:

  • 顺便说一句,要获取前两个字符,您需要[0:2] 或只需[:2]。正确的范围是[0:2][2:4][4:6]

标签: python string int comparison concatenation


【解决方案1】:

尝试添加这个:

hours = int(dur[0:2])
minutes = int(dur[2:4])
seconds = int(dur[4:6])

for n in range(0, LOOP):
    if(count == 0):
        # Check if hours is realistic
        if(hours > 0 and hours < 24 and hours < 10):
            ...

还有一个你不能用的东西hours = hours[1] 因为'int' object is not subscriptable

【讨论】:

    【解决方案2】:

    手动解析日期和时间是不值得的。您的代码尝试使用hours[0] 对整数进行索引。没有强制转换,字符串和整数类型是不可比较的。

    试试 Python 的 datetime 模块,特别是 strptime 函数,它从格式化的字符串中解析日期。您可以使用timedelta 提取小时、分钟、秒并轻松执行比较和加/减时间。

    from datetime import datetime
    
    while 1:
        try:
            dur = input("How long do you want to wait (EX: HHMMSS): ")
            dt = datetime.strptime(dur, "%H%M%S")
            print(dt, " hour:", dt.hour, " min:", dt.minute, " sec:", dt.second)        
            break
        except ValueError:
            print("Invalid time.")
    

    示例运行:

    How long do you want to wait (EX: HHMMSS): 012261
    Invalid time.
    How long do you want to wait (EX: HHMMSS): 012251
    1900-01-01 01:22:51  hour: 1  min: 22  sec: 51
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多