《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是强口令

如有错误,欢迎指出。如果疑问,我会再评论区回复。如果有更好的代码,希望能够分享一下。

相关推荐
biter down6 小时前
从 0 到 1 搭建 Python 接口自动化测试框架(博客系统实战)
开发语言·python
海南java第二人6 小时前
Nebula Graph 实战:基于图数据库存储 CMDB 实体关系
数据库·图数据库·nebula
曹牧7 小时前
oracle:“not all variables bound”
数据库·oracle
数据库百宝箱7 小时前
Oracle RMAN Image Copy 本地恢复
数据库·oracle
肖永威7 小时前
Python多业务并行计算框架插件化演进:从硬编码到动态注册
python·插件化·并行计算·动态注册
yz_aiks7 小时前
Linux Jar包配置Systemd自启动实战:从排查到配置全流程
linux·python·jar·自启动·systemd
AI智图坊7 小时前
多件装组合SKU图的批量生产效率分析:从PS手工到AI自动化的工作流改造
大数据·运维·人工智能·gpt·ai作画·自动化·aigc
不知名的老吴7 小时前
线程的生命周期之线程“插队“
java·开发语言·python
zuYM4g7Dp8 小时前
NoSql数据库设计心得
数据库·nosql
云烟成雨TD8 小时前
Spring AI 1.x 系列【56】用大模型评判大模型:递归顾问实现自动化评估方案
人工智能·spring·自动化