0
我期望下面的代码正常工作,因为第一个条件如果为false,但它通过IndexError: string index out of range
。我错过了什么?Python条件评估
a = False
sample_strign = 'test'
if (a == True) & (sample_strign[7] == 's'):
print('foo')
我期望下面的代码正常工作,因为第一个条件如果为false,但它通过IndexError: string index out of range
。我错过了什么?Python条件评估
a = False
sample_strign = 'test'
if (a == True) & (sample_strign[7] == 's'):
print('foo')
&
是一个按位运算符。如果您希望解释器将逻辑“短路”,请使用逻辑运算符and
。
if a and (sample_strign[7] == 's'):
sameple_strign
没有这将引发一个异常第七指数,你应该使用类似:
if a and len(sample_strign) > 7:
if sample_strign[7] == 's':
print('foo')
'&'是位运算符,并且不短路。 – user2357112
此外,检查只是'a'甚至'a是真的'比'a == True'更Pythonic –
[布尔运算符vs位运算符]的可能重复(https://stackoverflow.com/questions/3845018/布尔运算符-VS-按位运算符) –