1 #!/usr/bin/env python3.5
2 #coding:utf-8
3 import re 4
5 # 7.18.1
6
7 # 強口令檢測
8 # 寫一個函數,使用正則表達式,確保傳入的口令字符串是強口令
9 # 長度不少於8個字符,同時包含大小寫,至少有1個數字
10
11 pw = input("請輸入口令:") 12 def checkpw(passwd): 13 plen = len(passwd) 14 print(plen) 15 chpw1 = re.compile(r'.*[A-Z]+.*') 16 chpw2 = re.compile(r'.*[a-z]+.*') 17 chpw3 = re.compile(r'.*\d{1,}.*') 18 chresult1 = chpw1.search(passwd) 19 print("匹配大寫字符",chresult1) 20 chresult2 = chpw2.search(passwd) 21 print("匹配小寫字符",chresult2) 22 chresult3 = chpw3.search(passwd) 23 print("匹配至少1個數字",chresult3) 24 if (plen >= 8) and (chresult1 != None) and (chresult2 != None) and (chresult3 != None): 25 print("你的密碼符合要求") 26 else: 27 print("你的密碼不符合要求") 28
29 checkpw(pw) 30
31 #7.18.2
32 # 寫一個函數,它接受一個字符串,做的事情和strip()一樣
33 # 如果只傳入了要去除的字符串,沒有其它參數,那么就去除首尾空白字符
34 # 否則,函數第二個參數指定的字符將從該字符中去除
35
36 # 定義函數,傳遞2個參數:str1將被去除的字符串,str2接受用戶給定的原始字串
37 # 這里要注意:str1有默認值,要注意它的位置。
38
39 string = input("請給定一個待處理的原始字串:") 40 repstr = input("請輸入一個將被刪除的字串:") 41 def newstrip(str2,str1=''): 42 # 定義x,y變量用於向正則中傳遞,x用於匹配原始字串開頭的空白字符,y用於匹配原始字串結尾的空白字符
43 x = '^\s*'
44 y = '\s*$'
45 # 如果用戶沒有輸入將被刪除的字串,那么就返回去除頭尾空白字符的原始字串,否則返回被去除指定字串的新字串
46 if str1 == '': 47 newstr = re.sub(r'%s|%s'%(x,y),'',str2) 48 print("你沒有輸入將被去除的字符,默認將去除首尾空白字符如果有的話") 49 else: 50 newstr = re.sub(str1,'',str2) 51 print("字符" + str1 + "將從原始字串中被去除") 52 return newstr 53 print("處理后的字串為:") 54 if repstr in string: 55 print(newstrip(string,repstr)) 56 else: 57 print("你輸入的字串不在原始字串中,或者不連續")