Python 检查输入是否有数字?

Python check if a input has a digit in it?

我正在尝试查看如何查看用户输入中是否包含数字。我尝试使用 .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!')`

你可以试试re.search

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

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

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

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

使用any的好处是不会遍历整个字符串,第一次找到数字会return一个bool值!

等于休闲函数:

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