《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是强口令 ``` 如有错误,欢迎指出。如果疑问,我会再评论区回复。如果有更好的代码,希望能够分享一下。

相关推荐
Highcharts.js1 小时前
Highcharts Grid 中文站正式上线:表格数据处理的全新选择
前端·javascript·数据库·表格数据·highcharts·可视化图表·企业级图表
Elastic 中国社区官方博客4 小时前
Elasticsearch:使用 Agent Builder 的 A2A 实现 - 开发者的圣诞颂歌
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
2301_816660214 小时前
PHP怎么处理Eloquent Attribute Inference属性推断_Laravel从数据自动推导类型【操作】
jvm·数据库·python
第一程序员4 小时前
数据工程 pipelines 实践
python·github
知行合一。。。5 小时前
Python--05--面向对象(属性,方法)
android·开发语言·python
郝学胜-神的一滴5 小时前
深度学习必学:PyTorch 神经网络参数初始化全攻略(原理 + 代码 + 选择指南)
人工智能·pytorch·python·深度学习·神经网络·机器学习
qq_372154235 小时前
Go 中自定义类型与基础类型的显式转换规则详解
jvm·数据库·python
_下雨天.6 小时前
NoSQL之Redis配置与优化
数据库·redis·nosql
LiAo_1996_Y6 小时前
CSS如何实现文字渐变效果_通过background-clip实现艺术字
jvm·数据库·python
2401_887724506 小时前
CSS如何让表单在手机端友好展示_利用Flexbox实现堆叠排版
jvm·数据库·python