如何在字符串中搜索重复字符?

时间:2016-04-25 21:12:52

标签: python python-3.x

我正在尝试编写一个函数来检查字符串中的重复字符,如果找到重复则打印为false。像'hello16'或'secret77'之类的东西将是无效密码。

到目前为止我有什么

def password_check():
    if pw.isalpha() == True:
        print('Password must contain at least one number.')
    elif pw.isdigit() == True:
        print('Password must contain at least one letter. ')
    else:
        print('True')
pw = input('Enter new password: ') 

 #--------------------------------------------------- revised code below

def password_check(pw):
if len(pw) < 2:
    print ('Password must be at least 2 characters long')
elif pw.isalpha():
    print('Password must contain at least one number.')
    return False
elif pw.isdigit():
    print('Password must contain at least one letter. ')
    return False
for a in pw:
    if a * 2 in pw:
        print('Password contains a consecutive character')
        return False
print('Password was accepted')
return True

pw = input('Enter new password: ')
password_check(pw) # Call your function

2 个答案:

答案 0 :(得分:1)

一个非常简单的解决方案是:

def password_check(pw):
    if len(pw) < 2:
        print ('Password must be at least 2 characters long')
        return False
    elif pw.isalpha():
        print('Password must contain at least one number.')
        return False
    elif pw.isdigit():
        print('Password must contain at least one letter. ')
        return False
    for a in pw:
        if a * 2 in pw:
            print('Password contains a consecutive character')
            return False
    print('Password was accepted')
    return True

只需检查密码中出现的任何字符是否连续存在两次。

答案 1 :(得分:0)

使用groupby

from itertools import groupby

def password_check(pw):
    if not pw:
        print('Please enter a password')
    elif pw.isalpha():
        print('Password must contain at least one number.')
    elif pw.isdigit():
        print('Password must contain at least one letter. ')
    elif any((len(list(vals)) > 1) for (char, vals) in groupby(pw)):
        print('Password cannot contain duplicate characters. ')
    else:
        print('True')


pw = input('Enter new password: ')
password_check(pw) # Call your function