[英]Identify if there are two of the same character adjacent to eachother
我被要求創建一個程序,用於識別密碼是否有效。 我正在努力解決的一個問題是確定是否有兩個相同的字符彼此相鄰。 將不勝感激,這是迄今為止的計划:
import re
pswrd = input("Enter Desired Password:")
if len(pswrd) < 6:
print("Password must have more than 6 characters.")
if len(pswrd) > 15:
print("Password must have no more than 15 characters.")
if re.search("[$#@]",pswrd):
print("Password must have no special characters.")
if not re.search("[0-9]",pswrd):
print("Password must contain a number.")
if not re.search("[a-z]",pswrd):
print("Password must contain a lower case letter.")
if not re.search("[A-Z]",pswrd):
print("Password must contain an upper case letter.")
檢查相鄰字符的正則表達式是
(.)\1
句點(。)匹配任何字符。 括號在該字符周圍創建一個捕獲組,然后由\\ 1引用。
所以,條件是:
if re.search(r"(.)\1", pswrd)
注意正則表達式之前的r字符。 這使它成為一個原始字符串。 正則表達式應始終為原始字符串。 這可以確保正則表達式中的某些特殊字符(如\\ b)在傳遞給re模塊之前不會被解釋。
您可以在此處測試正則表達式: http : //regexr.com/3h0g0
我認為正則表達式r'(.)\\1'
應該做你想要的,其中\\1
是反向引用。
一種方法是使用any
和all
函數:
pswrd = input("Enter Desired Password:")
if any(all(b[0] == b[i] for i in range(len(b))) for b in [[pswrd[c], pswrd[c+1]] for c in range(len(pswrd)-1)]):
pass
您可以將密碼list()
列入並執行以下操作:
pswrd = 'assdfds'
pswrd = list(pswrd)
for i in range(len(pswrd)):
try:
if pswrd[i] == pswrd[i+1]:
a = True
break
except IndexError:
a = False
break
else:
continue
a = False
print(a)
返回True,如果存在彼此相鄰的兩個字母相同的點,則返回False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.