python if 'a' and 'b' and 'c' in 'abc'的坑

需求:想判断‘a’ ,‘b’ ,‘c’ 三个字符串都在‘abc’里在执行下条语句。
下面代码是错误的


    if 'a' and 'b' and 'c' in 'abc' :
    	print 'right'
    else :
    	print 'Error'	

正确写法

if 'a'  in 'abcd' and 'b' in 'abcd'  and 'c'  in 'abc' :
	print 'right'
else :
	print 'Error'	

原因:python中if判断条件是判断语句是否为true,什么条件为true?有字符时就为true(除了bool类型的false)。
按第一种写法这种情况是判断不出来的。

if 'xxxxxxxxxxxx' and 'ababababddddddddddd' and 'c' in 'abc' :
	print 'right'
else :
	print 'Error'	

执行结果是:right,因为只判断了 ‘c’ in ‘abc’。

猜你喜欢

转载自blog.csdn.net/u013908944/article/details/86475957
今日推荐