pyschools topic 3 ex 9

时间:2012-04-01 18:48:49

标签: python

我今天已经发了3篇关于pyschools.com练习的帖子,我希望这不是太多。无论如何,练习要求我写一个函数将时间转换为24小时格式。 这是一个例子:>>>时间24小时('12:34am')'0034hr'

我的功能,在我的IDLE中工作正常:

def time24hr(tstr):
    am_or_pm = tstr[-2:]
    first_numbers = tstr[0:2]
    last_numbers = tstr[3:5]
    if am_or_pm == "am":
        if first_numbers == '12':
            first_in_am12 = '00'
            return first_in_am12 + last_numbers + am_or_pm      
        else:
            return first_numbers + last_numbers + am_or_pm
    if am_or_pm == "pm":
        if first_numbers == '12':
            return first_numbers + last_numbers + am_or_pm
        elif int(first_numbers) > 9:
            ok = repr(int(first_numbers) + 12)
            return ok + last_numbers + am_or_pm
        elif int(first_numbers) <= 9:
            ok = repr(int(tstr[1]) + 12)
            return ok + last_numbers + am_or_pm

但是,在pyschools网站上,当我运行代码时,它会给我以下错误: ValueError:int()的基数为10的无效文字:'1:' 这是什么意思 ?

2 个答案:

答案 0 :(得分:4)

实际上您的代码不正确,并且您没有测试完整的测试用例。请考虑以下方案

>>> time24hr('2:34pm')

Traceback (most recent call last):
  File "<pyshell#855>", line 1, in <module>
    time24hr('2:34pm')
  File "<pyshell#849>", line 14, in time24hr
    elif int(first_numbers) > 9:
ValueError: invalid literal for int() with base 10: '2:'
>>> time24hr('2:34am')
'2:4aam'
>>> time24hr('0:34am')
'0:4aam'
>>> time24hr('12am')
'00mam'
>>> 

你会看到奇怪的结果

原因是,您假设输入始终采用HH:MM [am | pm]格式。您应该使代码灵活,以接受其他格式。

尝试使用split(':')代替first_numbers = tstr[0:2]last_numbers = tstr[3:5]

答案 1 :(得分:0)

def time24hr(tstr):
    time=tstr.replace(':','')
    if 'am' in time:
        tim=int(time.replace('am',''))
    elif 'pm' in time:
        tim=int(time.replace('pm',''))
    mini=tim%100
    hour=tim//100
    if mini<10:
    mini='0'+str(mini)
    else:
        mini=str(mini)
    if 'am' in time:
        if hour<10:
            hour='0'+str(hour)
    elif hour==12:
        hour='0'+str(hour-12)
        time1=time.replace('am','')
        time1=str(hour)+str(mini)+'hr'
    elif 'pm' in time:
        if hour<12:
            hour=12+hour
        elif hour==12:
            hour=hour
    time1=time.replace('pm','')
    time1=str(hour)+str(mini)+'hr'
    return time1

它可以在pyschools中使用