【问题标题】:Prevent input() from being anything but alphabet characters防止 input() 不是字母字符
【发布时间】:2018-01-26 12:06:26
【问题描述】:

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

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

【问题讨论】:

  • 是的,input 的结果在 Python 3 中将始终为str,即相当于 Python 2 的 raw_input。所以... "123" 是一个字符串,所以我不确定你想要什么。听起来您只想接受满足特定条件的字符串,例如“没有任何数字”,但是,您的其余条件并不明确,例如阻止“符号”...您应该尝试详细说明多一点以生成有用的答案。
  • 我修正了我提出问题的方式
  • 只有字母表中的字母是一个很好的规范,但是,只注意“或字符串”没有意义!字符串是一种数据类型! "123" 是一个字符串!
  • 我很抱歉。只有字母表中的字母
  • 不用道歉,当然不是因为开放学习!我要给你一个提示:记住,input 总是返回str 类型。现在,python 字符串有很多方便的方法,其中有.isalpha。我建议尝试一下,您将获得一半的解决方案!

标签: python string python-3.x input error-handling


【解决方案1】:

您可以使用str.isalpha 强制执行此要求。来自文档:

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

这是一个示例程序:

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

【讨论】:

  • @ChaseGrainger 很高兴帮助追逐。由于您似乎对 Python 较新(无意冒犯),因此请务必查看 Python docs。他们有大量的示例代码和信息。事实上,开始学习更多知识的好地方是official Python tutorial。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2011-03-01
    • 2011-10-25
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    相关资源
    最近更新 更多