【问题标题】:Can't change a string back to an integer in Python 3无法在 Python 3 中将字符串更改回整数
【发布时间】:2015-07-07 20:39:40
【问题描述】:
def get_time():
    start_time = str(input("Please enter the time you started working (hh:mm) "))
    if ":" in start_time:
        h1, m1 = start_time.split(":")
    else:
        h1 = int(start_time)
        m1 = " "
    if h1 < 8:
        print("You can't start working until 08:00.")
    elif h1 > 23:
        print("You can't work past 24:00 (midnight) ")
    end_time = str(input("Please enter the time you stopped working (hh:mm) "))

get_time()

这是我正在制作的一个程序的代码,用于记录有人照看孩子的时间。我无法将字符串数字转回整数。我得到错误:

  File "/Applications/Python 3.4/babysitting.py", line 10, in get_time
    if h1 < 8:
TypeError: unorderable types: str() < int()

为什么h1 = int(start_time) 不起作用?

【问题讨论】:

    标签: python string python-3.x int


    【解决方案1】:

    为什么h1 = int(start_time) 不工作?

    当您在输入中有 : 字符时,根本不会执行该行:

    if ":" in start_time:
        h1, m1 = start_time.split(":")
    else:
        h1 = int(start_time)
        m1 = " "
    

    int(start_time) 仅在输入中没有: 时执行,因此当if 测试为假时。

    将拆分和整数转换分开:

    h1 = start_time
    if ":" in start_time:
        h1 = start_time.split(":")[0]
    h1 = int(h1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 2023-03-16
      • 1970-01-01
      • 2013-04-23
      • 2013-04-25
      • 2016-12-29
      相关资源
      最近更新 更多