Python实践项目7.18

7.18.1 强口令检测

题目:

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

代码:

import re
text = str(input('输入一串口令:'))
def checkpw(text):
    flag = True
    if len(text) < 8:
        flag = False
    chpwRegex1 = re.compile(r'[a-z]')
    chpwRegex2 = re.compile(r'[A-Z]')
    chpwRegex3 = re.compile(r'[0-9]')
    if(chpwRegex1.search(text)==None) or (chpwRegex2.search(text)==None) or (chpwRegex3.search(text)==None):
        flag = False
    if flag:
        print('正确')
    else:
        print('错误')
checkpw(text)

运行结果:

输入一串口令:fghjkltyui67
错误

输入一串口令:GJutghiyg678
正确

7.18.2 strip()的正则表达式版本

题目:

写一个函数,它接受一个字符串,做的事情和 strip()字符串方法一样。如果只传入了要去除的字符串, 没有其他参数, 那么就从该字符串首尾去除空白字符。否则, 函数第二个参数指定的字符将从该字符串中去除。 

代码:

import re
def re_strip(text, chars=None):
    if chars is None:
        re_stripRegex = re.compile(r'^ *| *$')
    else:
        re_stripRegex = re.compile(r'^['+ chars + ']*|[' + chars +']*$')
    '''
    []的作用是某几个的范围 [abcd]
    '''
    return re_stripRegex.sub('',text)


print(re_strip('   123456   '))                # 123456
print(re_strip('   123456'))                   # 123456
print(re_strip('   123456    '))               # 123456
print(re_strip('123456   654321'))             # 123456   654321
print(re_strip('123456   654321', '1'))        # 23456   65432
print(re_strip('423456   654321', '1234'))     # 56   65
print(re_strip('123456   654321', '1234'))     # 56   65
print(re_strip('123456   654321', '124'))      # 3456   6543

运行结果:

123456
123456
123456
123456   654321
23456   65432
56   65
56   65
3456   6543

注:

strip()用法:

spam = 'SpamSpamBftyuyuiSpamgyuguySpamSpam'
spam.strip('ampS')

'BftyuyuiSpamgyuguy'

向strip()方法传入参数'ampS',告诉它在变量中存储的字符串两端,删除出现的a、m、p和大写的S。传入strip()方法的字符串中,字符的顺序并不重要:strip('ampS')做的事情和strip('mapS')或strip('Spam')一样。故在re_stripRegex = re.compile(r'^['+ chars + ']*|[' + chars +']*$')中需要用到中括号[]。

正则表达式中括号[]的作用:

1.某个区间内 如 [a-zA-Z0-9]
2.某几个的范围 [abcd]
3.可以在中括号中进行取非的操作. [^a]
4.在中括号中的字符不再有特殊的含义  如经常匹配全部的 .和*  [.][*]

猜你喜欢

转载自blog.csdn.net/sa_hao/article/details/81164547