简体   繁体   中英

How do i make a 5 letter username a requirement?

I have this code:

username=input("input username= ")
to_deny = ["!", "?", " ", "/", ",", ".", "[", "]", "(", ")",]
if any([char in username for char in to_deny]):
    print("denied characters: ?, !, space(s), /, dots, [], ()")
    quit()
else:
    print("hello",username,"!")

How can I make it so that the username must contain exactly 5 letters?

if any([char in username for char in to_deny]):
    print("denied characters: ?, !, space(s), /, dots, [], ()")
    quit()
elif len(username) != 5:
    print("username must be 5 characters")
    quit()
else:
    print("hello",username,"!")

I recommend you to use regex, it's really powerful and can be useful to know for harder requirements (eg : email validation, phone number validation, website validation)

import re

regex_condition = r"^[^!? \/,.[\]()]{5}$"
my_string = "aaaaa"

if (re.search(regex_condition, my_string)):
    print("String checked")
  1. ^ mean start of the string
  2. [^!? \/,.[\]()] [^!? \/,.[\]()] mean a single character NOT in !? \/,.[\]() !? \/,.[\]()
  3. {5} mean match the previous token (the single character not in the list) exactly 5 times
  4. $ mean end of the string

You can learn and train regex on https://regex101.com/

username=input("input username= ") to_deny = "!? /,.[]()" if any(char in username for char in to_deny): print("denied characters: ?, !, space(s), /, dots, [], ()") quit() elif len(username) != 5: print("username must be at least 5 characters") quit() else: print(f"hello {username}!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM