MEMER
MEMER

Reputation: 23

how can i make an input in python that only accepts capitalized letters and numbers

basically i need to get a variable as a user input (ch) that can only contain capitalized letters and numbers in form of a string of course . i tried to capitalize the input of the user even if he gave them in a lowercase format which worked fine but now i have to make sure he didn't use any signs (like what you see in forbidenCh) but my idea did not work pls help me out here you can use any methode you want as long as it accomplish's the purpose of the program and thnx

this is my attempt :

ch=str(input("only give letters and numbers"))
ch= ch.upper()
forbidenCh="!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
for i in forbidenCh:
 for j in ch:
   if i == j:
     ch=str(input("u didn't put captilized letters and numbers !!"))
     ch= ch.upper()
   else:
     break

Upvotes: 1

Views: 755

Answers (4)

fat mitchel 38
fat mitchel 38

Reputation: 54

ch = str(input("only give letters and numbers: "))
ch = ch.upper()
forbidden_chars = "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
# enter for-loop
for forbidden_chars in ch:
    # checking if forbidden_chars is in user input, if true ask for 
    # new input
    if forbidden_chars in ch:
        ch = str(input("u didn't put capitalized letters and numbers!: "))
        ch = ch.upper()
    else:
        break

Upvotes: 0

a121
a121

Reputation: 786

for such questions using ascii values is easier and efficient.

check this out

code:

n=input("enter a valid string")
for i in n:
    if ord(i) in range(65,91) or ord(i) in range(48,58):
        pass
    else:
        print("invalid")
        break

read more here

Upvotes: 0

J3rry
J3rry

Reputation: 11

you can do:

ch=str(input("only give letters and numbers"))
ch= ch.upper()
forbidenCh="!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"
for i in forbidenCh:
 if i in ch:
   ch=str(input("u didn't put captilized letters and numbers !!"))
   ch= ch.upper()

Upvotes: 0

Maurice Meyer
Maurice Meyer

Reputation: 18126

Probably it might be easier to check for allowed characters only:

import string
allowedCharacters = string.digits + string.ascii_uppercase
# allowedCharacters >> 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ

ch = str(input("only give letters and numbers"))
ch = ch.upper()

# check if all characters of the input are in allowedCharacters!
if not all(c in allowedCharacters for c in ch):
    print("u didn't put captilized letters and numbers !!")
else:
    print("input is fine")

Upvotes: 1

Related Questions