【问题标题】:Python - TypeError: unsupported operand type(s) for |: 'str' and 'str'Python - TypeError:不支持的操作数类型|:'str'和'str'
【发布时间】:2018-11-07 07:36:42
【问题描述】:

我正在尝试编写如下的 elif 条件:

if(type = a):
    do this
elif(type=b|c):
    do this
else:
    do this

我收到以下语句的错误

elif(type=b|c)

错误:

TypeError: unsupported operand type(s) for |: 'str' and 'str'

任何人都可以建议我在哪里出错。谢谢

【问题讨论】:

  • 你认为type=b|c 会做什么?
  • link 的可能重复文件

标签: python python-3.x operands


【解决方案1】:

这不是语法。

elif(type == b or type == c):

或:

elif(type in [b, c]):

【讨论】:

  • 假设 a、b、c 是字面上的字符串?就像 type == 'int' 其中 a 是 int 的替代品?这相当令人困惑。
【解决方案2】:

你的意思是(读 cmets):

if(type == a):
    do this
elif type in {b,c}: # i use `set` because it's the fastest # Also can do `type==b or type==c`
    do this
else:
    do this

【讨论】:

    【解决方案3】:

    使用这个:

    if(type == a):
            do this
        elif (type == b OR type == c):
            do this
        else:
            do this
    

    【讨论】:

      猜你喜欢
      • 2013-02-20
      • 2018-12-06
      • 1970-01-01
      • 2021-01-03
      • 2018-04-22
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      相关资源
      最近更新 更多