《python编程快速上手——让繁琐工作自动化》实践项目——强口令检测

题目:

写一个函数,它使用正则表达式,确保传入的口令字符串是强口令。强口令的定义是:长度不少于 8 个字符,同时包含大写和小写字符,至少有一位数字。你可能需要用多个正则表达式来测试该字符串,以保证它的强度。

个人思路:使用多个正则来确保各个条件符合。如果有一项符合则标记为True。如长度条件符合那么length = True。

长度:

python 复制代码
import re

def super_safe_pw(s):
    r = re.compile(r'.{8,}')
    e = r.search(s)
    length = 0
    if e is None: #r.search(s) is None 而不是e.group()
        print('长度低于8')

    else:
        print('长度合格')
        length = 1

定义函数super_safe_pw,参数为字符串s。

python 复制代码
r = re.compile(r'.{8,}')

'.'可以匹配除换行符外的所有字符{8,}表示至少8个

数字:

python 复制代码
r = re.compile(r'\d+')
    e = r.search(s)
    number = False
    if e is None:
        print('没有一个数字,不是强口令')
    else:
        print('数字合格')
        number = True

\d表示匹配数字,后面添加了一个'+',代表至少匹配一个数字。

小写:

python 复制代码
r = re.compile(r'[a-z]+')
    e = r.search(s)
    L_letters = False
    if e is None:
        print('没有小写字母')
    else:
        print('小写字母合格')
        L_letters = True

a-z\]直接匹配a到z内的字母,'\[a-z\]+'表示匹配一个或多个小写字母。 大写: ```python r = re.compile(r'[A-Z]+') e = r.search(s) U_letters = False if e is None: print('没有大写字母') else: print('大写字母合格') U_letters = True ``` \[A-Z\]匹配大写字母,'\[A-Z\]+'匹配一个或多个大写字母。 若 length is True and L_letters is True and U_letters is True and number is True,那么就是强口令了。 完整代码如下: ```python import re def super_safe_pw(s): r = re.compile(r'.{8,}') e = r.search(s) length = False if e is None: # r.search(s) is None 而不是e.group() print('长度低于8') else: print('长度合格') length = True r = re.compile(r'\d+') e = r.search(s) number = False if e is None: print('没有一个数字,不是强口令') else: print('数字合格') number = True r = re.compile(r'[a-z]+') e = r.search(s) L_letters = False if e is None: print('没有小写字母') else: print('小写字母合格') L_letters = True r = re.compile(r'[A-Z]+') e = r.search(s) U_letters = False if e is None: print('没有大写字母') else: print('大写字母合格') U_letters = True if length is True and number is True and L_letters is True and U_letters is True: print(f'{s}是强口令') else: print('不是强口令') d = 'jij25865Y' super_safe_pw(d) ``` 结果: ```python 长度合格 数字合格 小写字母合格 大写字母合格 jij25865Y是强口令 ``` 如有错误,欢迎指出。如果疑问,我会再评论区回复。如果有更好的代码,希望能够分享一下。

相关推荐
MATLAB代码顾问4 小时前
5大智能算法优化标准测试函数对比(Python实现)
开发语言·python
ting94520005 小时前
Tornado 全栈技术深度指南:从原理到实战
人工智能·python·架构·tornado
果汁华5 小时前
Browserbase Skills:让 Claude Agent 真正“看见“网页世界
人工智能·python
ZhengEnCi5 小时前
04-缩放点积注意力代码实现 💻
人工智能·python
DeepReinforce5 小时前
三、AI量化投资:使用akshare获取A股主板20260430所有的涨停股票
python·量化·akshare·龙头战法
HackTwoHub6 小时前
AI大模型网关存在SQL注入、附 POC 复现、影响版本LiteLLM 1.81.16~1.83.7(CVE-2026-42208)
数据库·人工智能·sql·网络安全·系统安全·网络攻击模型·安全架构
l1t6 小时前
DeepSeek总结的DuckLake构建基于 SQL 原生表格式的下一代数据湖仓
数据库·sql
段一凡-华北理工大学6 小时前
【高炉炼铁领域炉温监测、预警、调控智能体设计与应用】~系列文章08:多模态数据融合:让数据更聪明
人工智能·python·高炉炼铁·ai赋能·工业智能体·高炉炉温
万粉变现经纪人6 小时前
如何解决 pip install llama-cpp-python 报错 未安装 CMake/Ninja 或 CPU 不支持 AVX 问题
开发语言·python·开源·aigc·pip·ai写作·llama
KmSH8umpK6 小时前
Redis分布式锁从原生手写到Redisson高阶落地,附线上死锁复盘优化方案进阶第八篇
数据库·redis·分布式