【问题标题】:How to use multiple "or" in python code [duplicate]如何在python代码中使用多个“或”[重复]
【发布时间】:2017-10-17 11:01:38
【问题描述】:

我下面的代码只打印“删除特殊字符”。但如果我只离开(“#”),它运行得很好。

def name_character(word=input("Username: ")):
    if ("#") or ("$") or ("&") in word:
        return print ("Remove Special Character")
    if word == "":
        return print ("Enter Username")
    else: 
        return print (word)

(name_character())

【问题讨论】:

  • or 是一个布尔运算符,而不是英语语法结构。您需要明确:'#' in word or '$' in word or '&' in word.
  • @MartijnPieters 只需将字符串放入数组中即可:` chars = ['#', '$', '&'] `
  • @ghovat:是的,副本为您提供了更多选择。我只是指出了 OP 的尝试没有奏效的原因。
  • 另外,不要使用函数参数的默认值来要求用户输入。 input() 调用将被处理一次。见"Least Astonishment" and the Mutable Default Argument

标签: python python-3.x


【解决方案1】:

你的比较有点像这样

if("#" or .....)

并且在第一次比较时返回#。

做多个或比较,它会工作

def name_character(word=input("Username: ")):
    if (("#") in word )or (("$") in word ) or (("&") in word ) :
        return print ("Remove Special Character")
    if word == "":
        return print ("Enter Username")
    else: 
        return print (word)

(name_character())

【讨论】:

  • 谢谢拉森。你的建议很好
【解决方案2】:

试试这个:

>>> username = "foo#"
>>> any(x in username for x in "#&$")
True
>>> username = "bar"
>>> any(x in username for x in "#&$")
False

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 2011-11-18
    • 2021-03-16
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2014-10-14
    相关资源
    最近更新 更多