首页 > 解决方案 > 删除输入部分 - PYTHON

问题描述

我正在创建一个数模转换器。我有一个存储用户输入的变量,它应该是一个数字时间(例如 13:00)。然后我执行 inputVariable%12 以获取模拟时钟(例如 1)上的时间。但是,要做到这一点,我需要删除用户提供的任何额外信息(例如:00),所以我只存储了数字。我该怎么做呢?

time = input("Enter digital time here:\ne.g 12:00\n")
#Delete extra information here
time = int(time)
time = time%12
time = str(time)
print(time + " o'clock")

标签: pythonstringlistinteger

解决方案


我假设您的输入不会有任何错误(例如,用户输入了其他字符、超过 23 小时等)。考虑到您的输入格式,您应该首先拆分:. 这应该给你两个部分:小时和分钟。在此之后,您可以根据需要进行处理:

time = input("Enter digital time here:\ne.g 12:00\n")
hours, minutes = time.split(':')
hours = int(hours)
hours = hours % 12
hours = str(hours)
print(hours + " o'clock")

推荐阅读