python - 如何遍历字符串中的所有字符,然后检查是否有任何字符包含小写、大写、数字和标点符号并返回 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
解决方案
您在第一次迭代后返回;另外,你没有使用你的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
推荐阅读
- javascript - 如何更改表格单元格的颜色
- visual-studio-code - VSCode 终端建议未自动完成
- java - 如何在 Java 中写入命令提示符?
- kubernetes - 如果工作节点死亡,kubernetes 是否会恢复工作节点?
- scala - 实例化具有指定名称的类
- javascript - 如何使用 Quasar 构建微前端?
- wix - VS2019 中的 WiX 项目“不兼容”
- python - 如何使用一些条件(正则表达式?)修改熊猫中的一列字符串
- apache-spark - 预处理数据的最佳方法
- vb.net - VB.Net 表单身份验证 - Roles.CreateRole()