2017-10-02 10 views
0

私はユーザに文字列を入力させたいと思う簡単なプログラムをコーディングしています。文字列で許可されます)。Python:文字列内の特定の文字を別の文字列からチェックする方法

許可されていない文字列は、次のとおりです。たとえば

invalidChar = (@,#,£,{,[,},],:,;,",',|,\,/,?,~,`) 

、私が入力中の文字があることをユーザーに伝えるために、コードをご希望のユーザ入力「3testing @テスト」場合それは許可されていません。

私はもともと使用すると思った道:

if password[i]=="@": 
    booleanCheck = True 

が、これはオーバー数回繰り返さなければならないであろうと、これは厄介なコードのためになるだろう。

ありがとうございます!

+0

は、例えば、 '"(設定@ –

答えて

0

あなたはこのような文字のリストに対して文字テストすることができます。

invalidChar = ['@','#','£','{','[','}',']',':',';','"','\'','|', 
       '\\','/','?','~','`'] 

input_string = '[email protected]' 

# Let's define our logic in a function so that we can use it repeatedly 
def contains_invalid_char(s): # here we name our input string s 
    for element in s:   # lets iterate through each char in s 
     if element in invalidChar: # If its in the set, do the block 
      return True 
    return False    # If we made it this far, all were False 

# Then you can use the method to return a True or False, to use in a conditional or a print statement or whatever, like 

if contains_invalid_char(input_string): 
    print("It was a bad string") 
0

は無効な文字のsetを作成し、そのセットに対してパスワードの各文字を確認してください。

def has_invalid(password): 
    invalidChar = set(['@','#','£','{','[','}',']',':',';','"','\'','|','\\','/','?','~','`']) 
    return any(char in invalidChar for char in password) 

文字のいくつかはあなたがこのような何か行うことができます

0

をエスケープする必要があることに注意してください:あなたはこのために文字セットを使用することができます

>>> invalidChar = ('@','#') 
>>> password ="[email protected]" 
>>> if any(ch in password for ch in invalidChar): 
    booleanCheck = True 

>>> booleanCheck 
True 
+0

if文は必要ありません。単に 'booleanCheck = any(....)'を実行することができます – Wondercricket

+0

はい、あなたは正しいです。あなたに感謝@Wondercricketコメント –

関連する問題