确定是否有两个相邻字符相同的字符
我被要求创建一个程序来识别密码是否有效。我正在努力的一部分是确定是否有两个相同的字符彼此相邻。帮助将不胜感激,这里是节目至今:确定是否有两个相邻字符相同的字符
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.")
返回FALSE正则表达式来检查相邻字符是
(.)\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
你能详细说明所有这一切吗?我想在xrange(len(pswrd)-1)中有'all(pswrd [i]!= pswrd [i + 1])'不是更简单吗? – ryachza
你可以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,但如果还有点中彼此相邻的两个字母是相同
我刚刚意识到这是比其他更基本的__bit__ – AJ123
测试和最小密码长度不同意的答复。 (“少于6”不是“超过6”的相反) – trentcl