0

I have this code:

username=input("input username= ")
if "?" in username:
    print("the following characters are         allowed: a-z, -, num's")
    quit()
if "!" in username:
    print("only a-z, -, and num's are                 allowed")
    quit()
else:
    print("hello", username)

I want to simplify the code by putting all of the "denied" characters (here, ? and !) in the same line of code. How can I make the code work like that. I have tried using or and elif, but couldn't figure out a solution.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Why is this tagged `android`? – Scott Hunter Jun 14 '22 at 13:01
  • See this answer: https://stackoverflow.com/questions/19463556/string-contains-any-character-in-group – ivvija Jun 14 '22 at 13:01
  • @ScottHunter i tagged it as android because i use android, sorry for the confusion – IUseAndroidBtw Jun 14 '22 at 13:02
  • @ivvija i'll try it, be right back – IUseAndroidBtw Jun 14 '22 at 13:04
  • @ivvija i looked at the thread but i i don't really know how to implement and modify them to find a specific item – IUseAndroidBtw Jun 14 '22 at 13:08
  • " tagged it as android because i use android" Please don't do this. Tags are for identifying *what people need to know in order to answer the question properly*. Use the `android` tag only if the code uses Android-specific libraries, or if there is some other reason why an Android expert would have a special advantage in answering the question. – Karl Knechtel Jun 22 '22 at 08:59

2 Answers2

1

You can group the characters you want ignored in a list then use python's 'any' statment to check if any of the characters to be denied are found in username as follows :

username=input("input username= ")

# put unwanted chars here
to_deny = ['?', '!']

if any([char in username for char in to_deny]):
    print("only a-z, -, and num's are allowed")
    quit()
else:
    print("hello", username)
bmasri
  • 354
  • 1
  • 11
0

You might use set arithemtic to detect if string contain at least one of denied characters as follows

username=input("input username= ")
denied = {"?","!"}
if denied.intersection(username):
    print("username contain denied character or character, denied are:",*denied)
else:
    print("hello", username)
Daweo
  • 31,313
  • 3
  • 12
  • 25