這個問題在這里已經有了答案: 在 Python 中,如何檢查字串是否只包含某些字符? (8 個回答) 1 小時前關閉。
我需要檢查一個字串(密碼驗證器)是否在 python 中包含特定字符和長度。條件之一是,字串pwd 僅包含字符 a-z、AZ、數字或特殊字符“ ”、“-”、“*”、“/”。
塊參考
這些實用程式應該可以幫助我解決它(但我不明白):
- 使用isupper/islower決定一個字串是大寫還是小寫
- 使用isdigit檢查它是否是數字
- 使用in運算子檢查字串中是否存在特定字符。
pwd = "abc"
def is_valid():
# You need to change the following part of the function
# to determine if it is a valid password.
validity = True
# You don't need to change the following line.
return validity
# The following line calls the function and prints the return
# value to the Console. This way you can check what it does.
print(is_valid())
我很感激你的幫助!
uj5u.com熱心網友回復:
我們可以re.search在這里使用正則運算式選項:
def is_valid(pwd):
return re.search(r'^[A-Za-z0-9*/ -] $', pwd) is not None
print(is_valid("abc")) # True
print(is_valid("ab#c")) # False
uj5u.com熱心網友回復:
您可以使用正則運算式,但由于該任務僅涉及檢查字符是否屬于set,因此僅使用python set可能更有效:
def is_valid(pwd):
from string import ascii_letters
chars = set(ascii_letters '0123456789' '*- /')
return all(c in chars for c in pwd)
例子:
>>> is_valid('abg56*- ')
True
>>> is_valid('abg 56*')
False
使用正則運算式的替代方法:
def is_valid(pwd):
import re
return bool(re.match(r'[a-zA-Z\d* -/]*$', pwd))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/321762.html
上一篇:物體型別“X”需要定義一個主鍵
