【问题标题】:How do I check if a string contains ANY numbers [duplicate]如何检查字符串是否包含任何数字[重复]
【发布时间】:2015-09-14 00:24:33
【问题描述】:

我正在尝试验证用户名的输入。到目前为止,我可以阻止他们只输入数字,并使用 while 循环重复提示。如何阻止包含字母和数字的字符串被接受?

这是我目前所拥有的:

name = ""
name = input("Please enter your name:")
while name == "" or name.isnumeric() == True:
    name = input("Sorry I didn't catch that\nPlease enter your name:")

【问题讨论】:

    标签: python


    【解决方案1】:

    使用anystr.isdigit

    >>> any(str.isdigit(c) for c in "123")
    True
    >>> any(str.isdigit(c) for c in "aaa")
    False
    

    在你的情况下:

    while name == "" or any(str.isdigit(c) for c in name):
        name = input("Sorry I didn't catch that\nPlease enter your name:")
    

    您也可以使用str.isalpha:

    如果字符串中的所有字符都是字母并且至少有一个字符,则返回 true,否则返回 false。

    对于 8 位字符串,此方法取决于语言环境。

    我会像这样使用它来验证 "Reut Sharabani" 之类的东西:

    while all(str.isalpha(split) for split in name.split()):
    
        # code...
    

    它的作用是用空格分割输入,并确保每个部分都是字母。

    【讨论】:

    • 为什么不直接使用string.isalpha()
    • @Ben 只是因为标题,但你是对的 :) 已添加。
    • @ReutSharabani 你能告诉我如何将 str.isalpha() 合并到我的 while 循环中吗?我使用了您的第一个示例 Reut,但就像您说的那样,它仍然允许诸如“£*^$&^”之类的字符串是不可接受的名称
    • 答案的最后一行就是为了这个。确保您了解它的作用。
    • 感谢您的快速回复啊哈,但我现在刚刚解决了感谢您的帮助:)
    猜你喜欢
    • 2012-04-21
    • 2020-09-20
    • 1970-01-01
    • 2018-04-06
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    相关资源
    最近更新 更多