更新时间:2021-12-27 08:48:28
if 'Red' or 'red' in sheet['A2'].value:
始终被视为True
,因为非空字符串被视为True
.
所以实际上它与if True or 'red' in sheet['A2'].value:
if 'Red' or 'red' in sheet['A2'].value:
is always considered True
because non-empty strings are considered True
.
So in fact it's the same as if True or 'red' in sheet['A2'].value:
从文档中:
默认情况下,除非对象被其对象定义,否则其对象的类定义了返回False的
__bool__()
方法或返回零的__len__()
方法. 1 以下是大多数内置对象被认为是错误的:
By default, an object is considered true unless its class defines either a
__bool__()
method that returns False or a__len__()
method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
''
,()
,[]
,{}
,set()
,range(0)
0
, 0.0
, 0j
, Decimal(0)
, Fraction(0, 1)
''
, ()
, []
, {}
, set()
, range(0)
以下任何一种方法都可以解决您的问题:
any of the following would fix your problem:
if 'red' in sheet['A3'].value.lower():
或
if 'Red' in sheet['A3'].value or 'red' in sheet['A3'].value:
或
if any(color in sheet['A3'].value for color in ('Red', 'red')):
同样适用于所有if/elif条件.
另请注意,如果该字符串是较大字符串的一部分,它将仍然返回True,即
'Blue" in "I've Got The Blues"
将被评估为True
Same apply for all of your if/elif conditions.
Also note that if the string is part of bigger string it will still return True, i.e.
'Blue" in "I've Got The Blues"
will be evaluated True
由于评论中的讨论,我将评估"替换为考虑".
Because of discussion in the comments, I replace evaluate with considered.