如何检查字符串是否只包含小写字母和数字?

2024-04-24 21:58:21 发布

您现在位置:Python中文网/ 问答频道 /正文

如何检查字符串是否只包含数字和小写字母?

我只设法检查它是否包含数字和小写字母,并且不包含大写字母,但我不知道如何检查它是否不包含任何^&;*(%等)符号。。

if(any(i.islower() for i in password) and any(i.isdigit() for i in password) and not any(i.isupper() for i in password)):

编辑: 所以很显然,我需要在不使用任何循环的情况下,主要使用诸如.islower(),.isdigit(),isalnum()等函数来完成这项工作。。我不知道如何检查字符串是否只包含小写字母和数字,而不使用循环或其他检查字符串中每个字符的方法。我们只是开始学习python中的基础知识,所以他们告诉我们不能使用“for”,即使我知道它的用途。。现在我可以检查整个字符串是否只有数字或小写/大写字母,但我不知道如何用最简单的方法检查上面提到的两个条件


Tags: and方法字符串infor符号any数字
3条回答

怎么办:

if all(c.isdigit() or c.islower() for c in password):

毕竟,您需要检查所有字符是数字还是小写字母。所以对于所有字符c,这个字符就是c.isdigit() or c.islower()。现在,all(..)接受值的输入,并检查所有这些值的真实性是否为True。因此,从有一个数字不满足我们的条件起,all(..)将返回False

不过,请记住,如果没有元素,那么all(..)就是True。实际上,如果password是空字符串,则所有字符都满足此条件,因为没有字符。

编辑

如果要检查password是否同时包含数字和小写字符,可以将条件更改为:

if all(c.isdigit() or c.islower() for c in password) and \any(c.isdigit() for c in password) and \any(c.islower() for c in password):

现在,只有当password中至少有两个字符时,检查才会成功:一个较低的字符和一个数字。

另一种解决方案是计算每种类型的字母数,并确保它们不是零(在这种情况下,True等于1,False等于0):

def validate_password(password):
    """
    Return True if password contains digits and lowercase letters
    but nothing else and is at least 8 characters long; otherwise
    return False.

    """

    ndigits = sum(c.isdigit() for c in password)
    nlower = sum(c.islower() for c in password)
    password_length = len(password)
    return (password_length > 7 and ndigits and nlower and
            (ndigits+nlower)==password_length)

使用regex怎么样:

>>> def is_digit_and_lowercase_only(s):
        return re.match("^[\da-z]+$", s)
>>> print is_digit_and_lowercase_only("dA")
None
>>> print is_digit_and_lowercase_only("adc87d6f543sc")
<_sre.SRE_Match object at 0x107c46988>

如果匹配失败,它将返回None,因此可以与if一起使用。

相关问题 更多 >