如何在python中输入只接受大写字母和数字的内容
基本上,我需要一个变量作为用户输入(ch),它只能包含大写字母和数字,当然是字符串形式。我试图将用户的输入大写,即使他以小写格式输入,效果很好,但现在我必须确保他没有使用任何符号(如你在禁书中看到的),但我的想法不起作用,请帮我这里你可以使用任何你想要的方法,只要它达到程序和thnx的目的 这是我的尝试:如何在python中输入只接受大写字母和数字的内容,python,python-3.x,list,input,Python,Python 3.x,List,Input,基本上,我需要一个变量作为用户输入(ch),它只能包含大写字母和数字,当然是字符串形式。我试图将用户的输入大写,即使他以小写格式输入,效果很好,但现在我必须确保他没有使用任何符号(如你在禁书中看到的),但我的想法不起作用,请帮我这里你可以使用任何你想要的方法,只要它达到程序和thnx的目的 这是我的尝试: ch=str(input("only give letters and numbers")) ch= ch.upper() forbidenCh="!#$%&am
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
ch=str(输入(“仅给出字母和数字”))
ch=ch.upper()
禁止=“!\$%&'()*+,-./:;?@[\]^{124;}”
因为我在禁地:
对于ch中的j:
如果i==j:
ch=str(输入(“u没有输入大写字母和数字!!”)
ch=ch.upper()
其他:
打破
可能只检查允许的字符更容易:
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")
你可以做:
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()
ch=str(输入(“仅给出字母和数字”))
ch=ch.upper()
禁止=“!\$%&'()*+,-./:;?@[\]^{124;}”
因为我在禁地:
如果我在ch中:
ch=str(输入(“u没有输入大写字母和数字!!”)
ch=ch.upper()
ch=str(输入(“仅给出字母和数字:”)
ch=ch.upper()
禁止的字符=“!\$%&'()*+,-./:;?@[\]^{124;}”
#输入循环
对于ch中的禁用字符:
#检查用户输入中是否存在禁止字符,如果为true,则询问
#新输入
如果ch中禁止使用字符:
ch=str(输入(“u没有输入大写字母和数字!:”)
ch=ch.upper()
其他:
打破
对于此类问题,使用ascii值更简单有效
代码:
阅读更多内容你认为它不起作用是什么意思?这是否回答了你的问题?将
允许的字符
设置为一个集合也是一个好主意,这样就可以进行成员资格检查cheap@MEMER:排除列表的问题总是人们会忘记事情。在您的列表中,至少缺少一个空格
和°
,可能还有更多。作为提示,当其他用户来到这里寻找相同的答案时,请解释您的代码在做什么,他们也能理解
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
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