嵌套的If / Else控制流正在执行时不应该 - 逻辑操作错误

时间:2012-08-17 14:10:58

标签: python string if-statement logic

我有这段代码:

def time24hr(tstr):

    if ('a' and ':') in tstr:
        if tstr[:2] == '12':
            tstr = tstr.replace('12', '00').replace(':','').replace('am','hr')
            return tstr

        elif len(tstr[:tstr.find(':')]) < 2:
        # If length of string's 'tstr' slice (that ends before string ':') is less than 2
            tstr = tstr.replace(tstr[:tstr.find(':')],'0' + tstr[:tstr.find(':')]).replace(':', '').replace('am','hr')
            # Replace one-character string with combination of '0' and this one-character string. Then remove colon, by replacing it with lack of characters and replace 'am' string with 'hr'.
            return tstr

        else:
            tstr = tstr.replace(':', '').replace('am', 'hr')
            return tstr

    elif ('p' and ':') in tstr:
        tstr = tstr.replace(':', '').replace('pm', 'hr')
        return tstr

    else:
        return "Time format unknown. Type correct time."

当我执行此代码print time24hr('12:34am')时,它会返回0034hr字符串。 它也适用于此print time24hr('2:59am'),返回0259hr。但是当我在其中键入包含12的字符串时,它会自动省略代码if ('a' and ':') in tstr:或此elif ('p' and ':') in tstr:的这一部分并继续执行此部分:

if tstr[:2] == '12':
    tstr = tstr.replace('12', '00').replace(':','').replace('am','hr')
    return tstr

所以无论我输入12:15am还是12:15pm,这段代码如果在字符串中找到12,就会开始执行上面的代码。 print time24hr('12:15pm')会返回0015pm,但应返回0015hr,且仅适用于其中包含am的字符串。否则,请勿将12更改为00,并为1244hr返回12:44pm

我的问题是,为什么这些逻辑检查if ('a' and ':') in tstr:elif ('p' and ':') in tstr:不起作用? 此代码旨在成为此测验的解决方案 - &gt; http://www.pyschools.com/quiz/view_question/s3-q8

=============================================== ===================================

感谢您通过合理的操作帮助我。

此外,我已完成上述测验和此处的工作代码:

def time24hr(tstr):

    if (len(tstr[:tstr.find(':')]) == 2) and (tstr[0] == '0'):
        tstr = tstr.replace(tstr[0], '')

    if ('a' in tstr) and (':' in tstr):
        if tstr[:2] == '12':
            tstr = tstr.replace('12', '00').replace(':', '').replace('am', 'hr')
            return tstr

        elif len(tstr[:tstr.find(':')]) < 2:
        # If length of string's 'tstr' slice (that ends before string ':') is less than 2
            tstr = tstr.replace(tstr[:tstr.find(':')], '0' + tstr[:tstr.find(':')]).replace(':', '').replace('am', 'hr')
            # Replace one-character string with combination of '0' and this one-character string. Then remove colon, by replacing it with lack of characters and replace 'am' string with 'hr'.
            return tstr

        else:
            tstr = tstr.replace(':', '').replace('am', 'hr')
            return tstr

    elif ('p' in tstr) and (':' in tstr):
        if tstr[:2] == '12':
            tstr = tstr.replace(':', '').replace('pm', 'hr')
            return tstr

        elif len(tstr[:tstr.find(':')]) < 2:
            PmDict = {'0':'12','1':'13', '2':'14', '3':'15', '4':'16', '5':'17', '6':'18', '7':'19', '8':'20', '9':'21', '10':'22', '11':'23'}
            tstr = tstr.replace(tstr[:tstr.find(':')], PmDict[tstr[:tstr.find(':')]]).replace(':', '').replace('pm', 'hr')
            # Replace every "number" (which is string literally) with it's corresponding "number" in 24HR format, found in 'PmDict' dictionary. Then, as in above cases, remove colon ':' by replacing it with lack of character or space and then replace 'pm' with 'hr'
            return tstr

    else:
        return "Time format unknown. Type correct time."

我没有根据KISS规则编写这段代码,正如你所看到的那样 - 因为它有点复杂,但IMO工作得很好。

可以在这里测试 - &gt; http://doc.pyschools.com/console

为每个人欢呼并感谢您的帮助:)。

4 个答案:

答案 0 :(得分:6)

if ('a' and ':') in tstr:

相同
if ':' in tstr:

希望这能让您深入了解似乎存在的问题。

可能会替换为

if 'a' in tstr and ':' in tstr:

答案 1 :(得分:0)

你的第一次检查:

('a' and ':') in tstr

只是真正检查':'是否在tstr中。究竟是为什么这样,我不确定,但如果你在交互式Python中运行('a' and ':')语句,你会看到它返回':'。

您的第二次检查有同样的错误。

考虑使用

if ':' in tstr and 'a' in tstr:

elif 'p' in tstr and ':' in tstr:

不幸的是,Python只能像英语一样:)

答案 2 :(得分:0)

您的主要问题是您检查子字符串包含的代码是否错误:您使用in不正确。当你写

if ('a' and ':') in tstr:

首先评估('a' and ':')以获取:,然后检查if ':' in tstr。这就是第一个if块继续评估为true的原因。发生这种情况是因为and是布尔操作,x and y等同于x if bool(x) else y。在进行in检查之前,会对此表达式进行评估。

您可以用

替换该代码
if ('a' in tstr) and (':' in tstr)

(并为其他检查做同样的事情)

答案 3 :(得分:0)

您可以使用all来概括此测试是否存在多个元素:

if all(ch in tstr for ch in 'a:'):
    etc...