我有一个用Python制造的Discord机器人,用于查找用户名。用户名只能是A-z和0-9。 如何阻止人们使用特殊符号进行查询?
不允许的示例:
robotic@934!@
允许的示例:
Anf
GGDFG94
由于人们可以查找任何名称,所以只允许某些字符而不是完整的单词/单词的一部分将是有益的。
whitelist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
if SOMETHINGTOCOMPARE in whitelist:
print("You are allowed to look this username up.")
else:
print("Your username contains special characters. Disallowed.")
我将用户名存储在“响应”字符串中
答案 0 :(得分:3)
如果只想允许使用字母和数字,那么您所需要的只是str.isalnum
方法(“数字”代表“字母数字”):
if SOMETHINGTOCOMPARE.isalnum():
...
否则,其他答案中有几个选项。我个人将使用all
:
from string import digits, ascii_letters
whitelist = set(digits + ascii_letters + "#_-[]")
if all(c in whitelist for c in SOMETHINGTOCOMPARE):
...
答案 1 :(得分:0)
您只想检查一个集合中的字符,而不是其他集合中的字符,因此从根本上讲,您应该查看设置操作。
https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset
import string
def acceptable(querystring):
acceptable = set(string.ascii_letters + string.digits)
guess = set(querystring)
disallowed_characters_in_guess = guess - acceptable
return not bool(disallowed_characters_in_guess)
if acceptable("robotic@934!@"):
raise ValueError
if not acceptable("robotic934"):
raise ValueError
print ("okay")
答案 2 :(得分:0)
您可以检查SOMETHINGTOCOMPARE
是否是whitelist
(set)的子集:
def check(SOMETHINGTOCOMPARE):
whitelist = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
# Test whether every element in SOMETHINGTOCOMPARE is in whitelist.
if set(SOMETHINGTOCOMPARE) <= set(whitelist):
return True
return False
您可以使用以下方法测试该功能:
if check('robotic@934!@'):
print("You are allowed to look this username up.")
else:
print("Your username contains special characters. Disallowed.")
if check('Anf'):
print("You are allowed to look this username up.")
else:
print("Your username contains special characters. Disallowed.")
if check('GGDFG94'):
print("You are allowed to look this username up.")
else:
print("Your username contains special characters. Disallowed.")
答案 3 :(得分:0)
def checkifallowed(string):
whitelist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
for i in string:
if i not in whitelist:
return False
return True
somethingtocompare = input('What is the username that you want to look up?')
if checkifallowed(somethingtocompare):
print('You can search this name up')
else:
print('Disallowed.')
这只是定义一个函数,该函数检查白名单中的所有字符,并返回True或False。以下代码只是要求输入并返回结果。
答案 4 :(得分:0)
使用正则表达式查找模式匹配
pattern= r"^[a-z,A-Z,0-9\s]+$"
myval="robotic@934"
#cons,args=re.search(pattern,input).groups()
all_matches=re.findall(pattern, myval)
print(all_matches)
输出: []