Python 条件评估
Python conditional evaluation
我希望下面的代码能够正常工作,因为第一个条件如果为假,但它会通过 IndexError: string index out of range
。我错过了什么?
a = False
sample_strign = 'test'
if (a == True) & (sample_strign[7] == 's'):
print('foo')
&
是位运算符。如果您希望解释器 "short-circuit" 逻辑,请使用逻辑运算符 and
.
if a and (sample_strign[7] == 's'):
sameple_strign
没有会引发异常的第 7 个索引,您应该使用如下内容:
if a and len(sample_strign) > 7:
if sample_strign[7] == 's':
print('foo')
我希望下面的代码能够正常工作,因为第一个条件如果为假,但它会通过 IndexError: string index out of range
。我错过了什么?
a = False
sample_strign = 'test'
if (a == True) & (sample_strign[7] == 's'):
print('foo')
&
是位运算符。如果您希望解释器 "short-circuit" 逻辑,请使用逻辑运算符 and
.
if a and (sample_strign[7] == 's'):
sameple_strign
没有会引发异常的第 7 个索引,您应该使用如下内容:
if a and len(sample_strign) > 7:
if sample_strign[7] == 's':
print('foo')