防止input()只能是字母字符 [英] Prevent input() from being anything but alphabet characters

查看:53
本文介绍了防止input()只能是字母字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了自我了解,我正在尝试编写一个程序.我想问用户他们的名字是什么,我只希望用户能够使用字母表中的字母来回答,或者仅使用字符串.我不希望他们能够用数字,符号等来回答.

I am attempting to make a program for the sake of self-knowledge. I want to ask the user what their name is, and I only want the user to be able to use letters from the alphabet to answer, or only strings. I do not want them to be able to answer with numbers, symbols, etc.

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

推荐答案

您可以使用 str.isalpha .从文档中:

You can enforce this requirement using str.isalpha. From the documentation:

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

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as "Letter", i.e., those with general category property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different from the "Alphabetic" property defined in the Unicode Standard.

这是一个示例程序:

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

Note this method will not work for people with hyphenated names such as "Anne-Marie".

这篇关于防止input()只能是字母字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆