無效的密碼
這個網站專案的第二部分,是撰寫一支指令稿,用來驗證使用者輸入的密碼。 公司也訂了一些規則來判定密碼是否有效:
- 可以包含小寫
a-z與大寫字母A-Z - 可以包含數字
- 可以包含以下符號:
*、#、$、%、!、&、. - 長度至少要有 8 個字元,且不超過 20 個字元
你的同事也提供了一份密碼清單作為測試範例。
清單 passwords 與模組 re 已載入到你的工作階段。你可以在 IPython Shell 中使用 print(passwords) 檢視它們。
本練習屬於課程
Python 中的正規表示法
練習說明
- 撰寫一個正規表示式,依上述描述檢查密碼是否有效。
- 在
passwords清單中搜尋各元素,判斷它們是否為有效密碼。 - 若要印出是否為有效密碼的訊息,請完成
.format()敘述。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Write a regex to check if the password is valid
regex = ____"[____]____"
for example in passwords:
# Scan the strings to find a match
if re.____(____, ____):
# Complete the format method to print out the result
print("The password {____} is a valid password".format(pass_example=____))
else:
print("The password {____} is invalid".format(pass_example=____))