python笔记 多个字符串逻辑运算

python笔记 多个字符串逻辑运算

python用一个字符串变量和多个字符串比较的时候,不能用逻辑运算符直接连接几个字符串,例如

>>> str = 'abc'
>>> str == ('abcd' or 'abc')
False
>>> str = 'abc'
>>> str == ('abc' or 'abcd')
True

应将每个判断分开写

>>> str == 'abc' or  str == 'abcd'
True

这是因为,多个字符串进行逻辑or运算,返回第一个字符串,多个字符串进行逻辑and运算,返回最后一个字符串。

>>> str == 'abc' or  str == 'abcd'
True
>>> 'a' or 'b' or 'c'
'a'
>>> 'a' and 'b' and 'c'
'c'

如果逻辑运算式中有False, True, None等,输出与他们所在的位置有关,比较奇怪

>>> False or 'a' or 'b' or 'c'
'a'
>>> True or 'a' or 'b' or 'c'
True
'a' and 'b' and 'c' and True
True
'a' and 'b' and 'c' and False
False
>>> False and 'a' and 'b' and 'c'
False
>>> True and 'a' and 'b' and 'c'
'c'
>>> None or 'a' or 'b' or 'c'
'a'
>>> None and 'a' and 'b' and 'c'

你可能感兴趣的:(python)