首页 > 解决方案 > 如何遍历字符串中的所有字符,然后检查是否有任何字符包含小写、大写、数字和标点符号并返回 True

问题描述

我正在尝试检查字符串是否包含任何小写、大写、数字或标点符号,如果有则返回 True,但每当我运行它时,代码只检查第一个字符。我迭代不正确吗?

我尝试创建条件来检查字符是小写、大写、数字还是标点符号,如果是则返回 true。否则返回假。

这就是我目前所拥有的:

def check_characters(password, characters):
    '''Put your docstring here'''
    for i in password:
        if i.islower():
            return True
        if i.isupper():
            return True
        if i.isdigit():
            return True
        if i.punctuation():
            return True
        else:
            return False



def main():

    password = "n11+"
    print(check_characters(password, ascii_lowercase))
    print(check_characters(password, ascii_uppercase))
    print(check_characters(password, digits))
    print(check_characters(password, punctuation))

如果字符包含小写,我希望它为小写返回 True,并且对于其他函数调用相同,但是当它应该只对小写、数字和标点符号为真时,实际输出全部为 True

标签: python

解决方案


您在第一次迭代后返回;另外,你没有使用你的characters论点。

如果你遇到一个字符,你只想返回 true characters。如果您没有遇到任何此类字符,请返回 false:

from string import *

def check_characters(password, characters):
    # convert to set for better performance
    characters = set(characters)
    for i in password:
        if i in characters:
            return True
    return False


def main():
    password = "n11+"
    print(check_characters(password, ascii_lowercase))
    print(check_characters(password, ascii_uppercase))
    print(check_characters(password, digits))
    print(check_characters(password, punctuation))

您可以使用以下功能简化此操作any

def check_characters(password, characters):
    # convert to set for better performance
    characters = set(characters)
    return any(i in characters for i in password)

无论如何,在这两种情况下,运行main都会输出:

True
False
True
True

推荐阅读