I would like to make (input) function accepts uppercase letters or numbers only in python? I mean how can I force the user to use uppercase letters or numbers only.
Thank you in advance.
I would like to make (input) function accepts uppercase letters or numbers only in python? I mean how can I force the user to use uppercase letters or numbers only.
Thank you in advance.
You can use all(char in string.ascii_uppercase for char in data)
with a while
loop:
import string
data = input('Please enter a fully-uppercased string: ')
while not all(char in string.ascii_uppercase for char in data):
data = input('Please enter a fully-uppercased string: ')
You could simply do something like
x = input().upper()
Which would take the input then turn it into uppercase. Though I would suggest adding some code into your post just to make sure this is a viable option
A skeleton:
import sys
import termios
import fcntl
import os
def getchar():
fd = sys.stdin.fileno()
oldatribut = termios.tcgetattr(fd)
newatribut = termios.tcgetattr(fd)
newatribut[3] = newatribut[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newatribut)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
mychar = None
try:
mychar = sys.stdin.read(1)
except IOError:
pass
termios.tcsetattr(fd, termios.TCSAFLUSH, oldatribut)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
return mychar
def filter():
my_char = getchar()
if my_char.isupper() or my_char.isnumeric() or my_char == "\n":
return my_char
return ""
def my_input(your_question=""):
theorem = ""
print(your_question, end='', flush=True)
while True:
mychar = filter()
if mychar:
theorem += mychar
print(mychar, end='', flush=True)
if mychar == "\n":
return theorem
my_string = my_input("Only uppercase or digit: ")
print("your answer: " + my_string)
Attention, work only in terminal!