我是 Python 的新手。
我试图确保用户名仅包含字母字符(仅 az)。我有以下代码。如果我只输入数字(例如 7777),它会正确地抛出错误。如果我输入数字和字母混合,但我以数字开头,它也会拒绝。但是,如果我以字母 (az) 开头,然后字符串中也包含数字,则它会接受它是正确的。为什么?
def register():
uf = open("user.txt","r")
un = re.compile(r'[a-z]')
up = re.compile(r'[a-zA-Z0-9()$%_/.]*$')
print("Register new user:\n")
new_user = input("Please enter a username:\n-->")
if len(new_user) > 10:
print("That username is too long. Max 10 characters please.\n")
register()
#elif not un.match(new_user):
elif not re.match('[a-z]',new_user):
print("That username is invalid. Only letters allowed, no numbers or special characters.\n")
register()
else:
print(f"Thanks {new_user}")
Run Code Online (Sandbox Code Playgroud)
你为什么不使用isalpha()?
string = '333'
print(string.isalpha()) # False
string = 'a33'
print(string.isalpha()) # False
string = 'aWWff'
print(string.isalpha()) # True
Run Code Online (Sandbox Code Playgroud)