我正在编写一个简单的程序,我希望用户输入一个字符串,然后我的代码将检查另一个字符串(字符串中不允许)。
不允许的字符串是:
invalidChar = (@,#,£,{,[,},],:,;,",',|,\,/,?,~,`)
例如,如果用户输入"测试@ 3测试"我希望代码告诉用户输入中有一个不允许的字符。
我最初的想法是使用:
if password[i]=="@":
booleanCheck = True
但是这必须重复多次,这会导致代码混乱。
提前致谢!
答案 0 :(得分:0)
您可以根据以下字符列表测试角色:
invalidChar = ['@','#','£','{','[','}',']',':',';','"','\'','|',
'\\','/','?','~','`']
input_string = 'testing@3testing'
# 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")
答案 1 :(得分:0)
制作set
个无效字符,然后根据该集检查密码中的每个字符。
def has_invalid(password):
invalidChar = set(['@','#','£','{','[','}',']',':',';','"','\'','|','\\','/','?','~','`'])
return any(char in invalidChar for char in password)
请注意,某些字符需要转义
答案 2 :(得分:0)
您可以这样做:
>>> invalidChar = ('@','#')
>>> password ="testing@3testing"
>>> if any(ch in password for ch in invalidChar):
booleanCheck = True
>>> booleanCheck
True