首页 > 解决方案 > 我怎样才能在python中输入只接受大写字母和数字

问题描述

基本上我需要获取一个变量作为用户输入(ch),当然它只能包含大写字母和数字。我试图将用户的输入大写,即使他以小写格式提供它们,效果很好,但现在我必须确保他没有使用任何符号(就像你在 forbidenCh 中看到的那样),但我的想法没有奏效在这里帮助我,您可以使用任何您想要的方法,只要它完成程序的目的和thnx

这是我的尝试:

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

标签: pythonpython-3.xlistinput

解决方案


可能只检查允许的字符可能更容易:

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")

推荐阅读