且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Excel单元格复制值并将其按比例粘贴到新单元格中

更新时间: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:

  • 常量定义为false:无"和"False".
  • 任何数字类型的零:00.00jDecimal(0)Fraction(0, 1)
  • 空序列和集合:''()[]{}set()range(0)
  • constants defined to be false: None and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, 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.