【问题标题】:how can i make an input in python that only accepts capitalized letters and numbers我怎样才能在python中输入只接受大写字母和数字
【发布时间】:2020-11-29 13:20:12
【问题描述】:

基本上我需要获取一个变量作为用户输入(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

【问题讨论】:

标签: python python-3.x list input


【解决方案1】:

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

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

【讨论】:

  • allowedCharacters 设置为一组以便会员检查便宜
  • @MEMER:排除列表的问题总是,人们忘记了事情。在您的列表中,至少缺少 whitespaces°,而且可能还有更多。
【解决方案2】:
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

【讨论】:

  • 作为提示,请解释您的代码在做什么,这样当其他用户来到这里寻找相同的答案时,他们也可以理解它
【解决方案3】:

你可以这样做:

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

【讨论】:

    【解决方案4】:

    对于此类问题,使用 ascii 值更容易且高效。

    check this out

    代码:

    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
    

    阅读更多here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多