代码之家  ›  专栏  ›  技术社区  ›  Geuis

检查字符串是否包含一个值或另一个值,语法错误?

  •  2
  • Geuis  · 技术社区  · 16 年前

    我是从javascript后端到Python的,遇到了一个基本但令人困惑的问题

    我有一个字符串,可以包含“left”、“center”或“right”值。我正在测试变量是否包含“left”或“right”。

    在js中很简单:

    if( str === 'left' || str === 'right' ){}
    

    if str == 'left' || str == 'right':
    

    为什么这不起作用,正确的语法是什么?

    1 回复  |  直到 16 年前
        1
  •  13
  •   kennytm    16 年前

    蟒蛇的 logical OR operator 被称为 or . 没有 || .

    if string == 'left' or string == 'right':
    ##                  ^^
    

    if string in ('left', 'right'):
    
    ## in Python ≥3.1, also possible with set literal
    ## if string in {'left', 'right'}:
    

    还要注意 str is a built-in function 在巨蟒中。您应该避免命名与它们冲突的变量。