【发布时间】:2012-02-13 17:58:39
【问题描述】:
所以我承认这是一项家庭作业,但我并不是要你们所有人为我做这件事,我只是在寻求一些指导。我们需要让 Python 程序在单个字符串中接受 Hours:Minutes (2:30) 格式的时间,并以分钟为单位输出时间量。 (即 2 小时 30 分钟 = 150 分钟)
我仍然需要解决字符串输入的一些限制:
- 确保它只使用数字和冒号
- 确保它只能接受五个字符 (##:##)
- 确保中间字符是冒号(即数字的顺序正确)
- 并确保如果输入像 4:35 这样的时间,会在前面自动添加一个零
我稍后会处理这个问题——现在我决定处理从输入中得到的数学。
对我来说,将字符串分成两部分是有意义的:小时和分钟。然后,我将小时数乘以 60,并将它们添加到预先存在的分钟数中以获得总分钟数。 However, right now, entering a time like 02:45 is outputting a minute amount of 02020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020245.
知道这里可能出了什么问题吗?需要说明的是,这是作业,我想自己解决输入限制,我只需要帮助解决这个数学问题。
#Henry Quinn - Python Advanced 4.0 Hours and Minutes
import re
print "This program takes an input of time in hours and minutes and outputs the amount of minutes."
count = 0
#I still need to work out while loop
#Supposed to make sure that a time is entered correctly, or error out
while (count <1):
time = raw_input("Please enter the duration of time (ex: 2:15 or 12:30): ")
if not re.match("^[0-9, :]*$", time):
print "Sorry, you're only allowed to use the numbers 0-9."
elif len(time) > 5:
print "Sorry, only five characters max allowed."
#MAKE THIS CHECK FOR A COLON
#elif
#elif
else:
count = count + 1
#If time = 12:45, hours should be equal to 12, and minutes should be equal to 45
hours = time[:2]
minutes = time[3:]
#Should convert hours to minutes
newhours = hours * 60
#Should make total amount of minutes
totalminutes = newhours + minutes
print "The total amount of elapsed minutes is %s" % (totalminutes)
raw_input("Please press Enter to terminate the program.")
【问题讨论】:
-
将一个字符串乘以一个整数会生成一个包含许多原始字符串副本的字符串。先在数字字符串上调用
int()。
标签: python string math string-split