Python如何检查输入中是否包含数字?

3

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

https://docs.python.org/2/library/re.html - cdarke
@vinash-raj回答了你的问题,但你真的应该考虑使用https://github.com/dropbox/zxcvbn(或https://github.com/dropbox/python-zxcvbn作为Python版本)来解决你的问题。 - bufh
2个回答

5

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

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

使用any的优点在于它不会遍历整个字符串,如果第一次找到数字,它将返回一个布尔值!这等同于以下函数:
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")

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接