所以我寫了這段代碼來查找我的字串中是否有大寫字母和數字,這是我目前所擁有的
def passwordOK(password: str):
for char in password:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "1234567890":
return True
else:
return False
print(passwordOK(password='roskaisHsodihf'))
但結果只有在第一個變數被修改時才會回傳,所以如果第一個變數是數字或大寫字母,輸出只列印 True 應該對我的代碼進行哪些更改?
請不要使用 import 并盡量使用盡可能少的內置函式
uj5u.com熱心網友回復:
def passwordOK(txt):
return True if any(t.isupper() for t in txt) and any(t.isdigit() for t in txt) else False
uj5u.com熱心網友回復:
3個問題:
- 你總是從第一次回圈迭代回傳
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "1234567890"并不意味著你認為它的作用。- 如果是這樣,你的邏輯仍然是錯誤的。字符不能同時是大寫字母和數字。如果你的意思是
or,兩者中的一個仍然不能確認另一個位置上另一個的存在。
您需要的邏輯應該遵循以下幾行:
def passwordOK(password: str):
upper = digit = False
for char in password:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "1234567890":
upper = True
if char in "1234567890":
digit = True
if upper and digit:
return True
return False
如果您要使用一些實用程式,則可以避免一些樣板代碼:
from string import ascii_uppercase, digits
def passwordOK(password: str):
upper = any(c in ascii_uppercase for c in password)
digit = any(c in digits for c in password)
return upper and digit
或者更短,使用測驗方法:
def passwordOK(password: str):
return any(map(str.isupper, password)) and any(map(str.isdigit, password))
uj5u.com熱心網友回復:
根據您的代碼判斷,邏輯比較并不像您期望的那樣作業。and關鍵字左側和右側的每個部分都將回傳True或False。因此,您需要重復char變數以檢查您的第二個字串列,如下所示:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and char in "1234567890":
True在這種情況下,默認情況下將回傳一個非空字串。
編輯:
您也必須使用,or因為and只有True在滿足兩個 creterias時才會回傳。單個字符不能同時位于兩個不相交的集合中。
這里的一種方法是在滿足任一條件時設定變數,并且只要滿足兩個條件,就回傳True。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/357896.html
