【问题标题】:Python check if a input has a digit in it?Python检查输入中是否有数字?
【发布时间】:2015-07-01 09:35:09
【问题描述】:

我正在尝试查看如何查看用户输入中是否有数字。我尝试使用.isdigit(),但只有在它只是一个数字时才有效。我试图将其添加到密码检查器中。我也试过.isalpha(),但没用。我做错了什么,我需要添加或更改什么?

这就是我所拥有的

   password = input('Please type a password ')
   str = password
   if str.isdigit() == True:

    print('password has a number and letters!')
    else:
            print('You must include a number!')`

【问题讨论】:

标签: python string input numbers python-3.4


【解决方案1】:

您可以在any 函数中使用生成器表达式和isdigit()

if any(i.isdigit() for i in password) :
       #do stuff

使用any的好处是它不会遍历整个字符串,如果第一次找到一个数字就会返回一个bool值!

相当于休闲功能:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

【讨论】:

    【解决方案2】:

    你可以试试re.search

    if re.search(r'\d', password):
         print("Digit Found")
    

    并且不要使用内置数据类型作为变量名。

    【讨论】:

      猜你喜欢
      • 2013-12-04
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 2020-04-03
      • 2016-03-30
      • 1970-01-01
      相关资源
      最近更新 更多