Hen*_* IV 4 python string math string-split
所以我承认这是一个家庭作业,但我并不是要求你们为我做这件事,我只是在寻找一些指导.我们需要制作一个Python程序,以单个字符串中的小时:分钟(2:30)格式接受时间,并输出以分钟为单位的时间量.(即2小时30分钟= 150分钟)
我仍然需要解决字符串输入的一些限制:
我稍后会解决这个问题 - 现在我决定从输入中得到数学.
将字符串分成两部分是有意义的:小时和分钟.然后,我将小时数乘以60,并将它们添加到预先存在的分钟数,以获得总分钟数.但是,现在,进入02:45的时间输出分钟金额为020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020245.
知道这里可能出了什么问题吗?需要明确的是,这是家庭作业,我想自己解决输入限制,我只需要帮助解决这个数学问题.
#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.")
Run Code Online (Sandbox Code Playgroud)
现在,小时和分钟是字符串变量,而不是整数.因此,你不能像数字那样乘以它们.
将第20行和第21行更改为
hours = int(time[:2])
minutes = int(time[3:])
Run Code Online (Sandbox Code Playgroud)
并且在02:45投入应该可行.但是,如果你没有领先0(如果你放入2:45),你仍会遇到问题,所以我建议你把它拆分为":",如下所示:
hours = int(time.split(":")[0])
minutes = int(time.split(":")[1])
Run Code Online (Sandbox Code Playgroud)