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")
^
mean start of the string [^!? \/,.[\]()]
[^!? \/,.[\]()]
mean a single character NOT in !? \/,.[\]()
!? \/,.[\]()
{5}
mean match the previous token (the single character not in the list) exactly 5 times $
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.