2017-09-05 119 views
0

我期望下面的代码正常工作,因为第一个条件如果为false,但它通过IndexError: string index out of range。我错过了什么?Python条件评估

a = False 
sample_strign = 'test' 
if (a == True) & (sample_strign[7] == 's'): 
     print('foo') 
+4

'&'是位运算符,并且不短路。 – user2357112

+4

此外,检查只是'a'甚至'a是真的'比'a == True'更Pythonic –

+2

[布尔运算符vs位运算符]的可能重复(https://stackoverflow.com/questions/3845018/布尔运算符-VS-按位运算符) –

回答

6

&是一个按位运算符。如果您希望解释器将逻辑“短路”,请使用逻辑运算符and

if a and (sample_strign[7] == 's'): 
1

sameple_strign没有这将引发一个异常第七指数,你应该使用类似:

if a and len(sample_strign) > 7: 
    if sample_strign[7] == 's': 
     print('foo')