【问题标题】:How do I only allow letters when asking for a name in python? [duplicate]在 python 中询问名称时如何只允许字母? [复制]
【发布时间】:2017-01-05 01:37:47
【问题描述】:

我是 python 编码的新手,需要知道如何只允许用户在输入名称时输入字母。因此,如果他们输入数字或根本不输入数字,我希望代码显示“请仅使用字母,再试一次”。

克里斯干杯

【问题讨论】:

    标签: python string input


    【解决方案1】:

    您要求的是str.isalpha() 函数:

    isalpha(...)
       S.isalpha() -> bool
    
       Return True if all characters in S are alphabetic
       and there is at least one character in S, False otherwise.
    

    例如你可以这样使用它:

    def ask_name():
        while True:
            name = raw_input("What is your name?")
            if name.isalpha():
                return name
            else:
                print("Please use only letters, try again")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-06
      • 1970-01-01
      • 2019-02-10
      相关资源
      最近更新 更多