代码之家  ›  专栏  ›  技术社区  ›  dumb dirty

python“in”操作将字符串与仅包含1个字符串的元组进行比较

  •  0
  • dumb dirty  · 技术社区  · 2 年前

    当比较一个字符串和一个只包含1个字符串的元组时,我注意到“in”操作的一个奇怪行为。

    'monday' in ('not monday')
    


    好像我们在比较两个字符串

    但是如果我通过在元组中添加另一个元素来更改表达式。

    'monday' in ('not monday', 'not monday neither')
    

    知道为什么吗?

    2 回复  |  直到 2 年前
        1
  •  4
  •   Green Cloak Guy    2 年前
    >>> 'monday' in ('not monday')
    True
    >>> 'monday' in ('not monday',)
    False
    

    单元素元组 必须 'monday' in ('not monday') 在语法上与相同 'monday' in 'not monday' .

        2
  •  0
  •   normidar    2 年前

    因为 ('not monday') 不表示元组,它表示与相同的字符串 'not monday' ,如果只想创建一个单位元组,可以编写 ('not monday',) , 直到最后)。

    祝你好运