在if / else语句中使用substring的问题

时间:2014-02-22 02:03:13

标签: python substring

我有一些我想要返回的代码'正确'如果参数中的前两个字符是CHDLPR

def validation_check(trans):
    #Make sure the transaction is in proper format
    r = re.compile('.. .. ......')
    if r.match(trans) is None:
        f = open("validation.errors.log", "a")
        f.write(trans+'-Improper format' '\n')
        f.close()
    elif trans[0:1] != 'CH' or 'DL' or 'PR':
        f = open("validation.errors.log", "a")
        f.write(trans+ "-Invalid action" '\n')
        f.close()
        return "That is not a valid action!"
    else:
        return "right"

print (validation_check('CH SE NST231 072 00/01/23'))

但由于某种原因,它会继续执行elif语句,任何帮助吗?

2 个答案:

答案 0 :(得分:2)

In [507]: trans='CHasdf'

In [508]: trans[0:1] != 'CH' #you should use [0:2]
Out[508]: True

In [509]: trans[0:2]
Out[509]: 'CH'

#and "x!= 1 or 2" is not what you want:
In [525]: trans[0:2] != 'CH' or 'DL' or 'PR'
Out[525]: 'DL'

#it evaluates "!=" first, then "or"
In [526]: (trans[0:2] != 'CH') or 'DL' or 'PR'
Out[526]: 'DL'

#use "not in a_list_of_your_candidates":
In [527]: trans[0:2] not in ('CH', 'DL', 'PR')
Out[527]: False

答案 1 :(得分:1)

if 3 == 4 or 5:
   print 'true'

打印'true'

为什么呢?因为“3等于4”“5是真正的”。

你想要

elif trans[0:2] not in ('CH' , 'DL' , 'PR'):

(注意:它是[0:2]“从索引0开始的子字符串和_继续两个字符” - 不是“直到索引1”,你似乎在思考。)