防止 input() 为字母字符以外的任何内容

问题描述 投票:0回答:3

我尝试制作一个程序是为了自知之明。我想问用户他们的名字是什么,并且我只希望用户能够使用字母表中的字母来回答,或者仅使用字符串。我不希望他们能够用数字、符号等来回答。

def cc():
  name = (input("""Hello, what happens to be your first name?  
        > """))
  if type(name) is str:
      print("You have entered a name correctly.")
  elif type(name) is int:
      print("Your name cannot be an integer. Try again.")
      cc()

cc()
python string python-3.x input error-handling
3个回答
5
投票

您可以使用

str.isalpha
强制执行此要求。来自文档:

如果字符串中的所有字符都是字母且至少有一个字符,则返回 true,否则返回 false。字母字符是在 Unicode 字符数据库中定义为“Letter”的字符,即具有一般类别属性为“Lm”、“Lt”、“Lu”、“Ll”或“Lo”之一的字符。请注意,这与 Unicode 标准中定义的“字母”属性不同。

这是一个示例程序:

while True:
    name = input('Enter a name using only alphabetic characters: ')
    if name.isalpha():
        break

演示:

Enter name using only alphabetic characters:  Bo2
Enter name using only alphabetic characters:  Bo^&*(
Enter name using only alphabetic characters:  Bob

请注意,此方法不适用于名称带有连字符的人,例如 “Anne-Marie”


0
投票

我同意这个问题有点误导。但是,根据您所说的,您只需要使用正则表达式即可完成此操作。

import re
...
if not re.findall('[^a-zA-Z]', 'abc1'):
   print("You have entered a name correctly.")
else
   print("Your name cannot be an integer. Try again.")
   cc()

0
投票

前面所述的答案有效,但有点过于复杂,只需执行以下操作:

def cc():
    name = (input("""Hello, what happens to be your first name?  
    > """))
    try:
        for letter in name:
            int(letter)
    except ValueError:
        print("You have entered a name correctly")
    else:
        print("Your name cannot be an integer, try again!")
        cc()

cc()
© www.soinside.com 2019 - 2024. All rights reserved.