2017-10-17 435 views
1

我的下面的代碼只打印「刪除特殊字符」。但如果我只留下(「#」),它運行得非常好。如何在Python代碼中使用多個「或」

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()) 
+0

'或'是一個布爾運算符,而不是英語語法結構。您需要明確:單詞中的'#'或單詞中的'$'或單詞中的'&'。 –

+0

@MartijnPieters只需將字符串放在數組中: 'chars = ['#','$','&']' – ghovat

+1

@ghovat:是的,重複給你更多的選擇。我只是在指出OP的嘗試失敗的原因。 –

回答

0

您的比較是有點轉向這樣

如果( 「#」 或.....)

和#在第一次比較中返回。

做到在多個或比較,它會工作

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()) 
+1

謝謝Rathan。你的建議運行良好 – Albert

0

試試這個:

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