Python 密码中的一个特殊字符

Python one special character in password

我有一个小问题,因为我想检查用户密码并强制必须使用一个特殊字符。但是在我的输出中,即使创建了密码,我也会收到一条无效消息。我该如何修复这个东西?

special_character= '$#!'


created = False
while not created:
    password = input('Type your password: ')
    for char in special_character:
        if char in password:
            print('Password Created!!')
            created = True
    else:
        print('Sorry, try again!')

Output:
Type your password: MyStronPassword123$
Password Created!!
Sorry, try again!

如何丢弃此文本:“抱歉,请重试”

您应该使用 if 语句来查看密码是否已创建。

special_character= '$#!'

created = False
while not created:
    password = input('Type your password: ')
    for char in special_character:
        if char in password:
            print('Password Created!!')
            created = True
    if not created:
        print('Sorry, try again!')

输出:

输入您的密码:MyStronPassword123$

密码已创建!!

尝试使用以下方法:

sc = '$#!'
ps = "test!"
for i in sc:
    if i in ps:
        print("GOOD")
        break

您的 else 语句将始终执行,我想您希望它仅在 for 循环中断时才执行,在这种情况下添加 break :

special_character= '$#!'


created = False
while not created:
    password = input('Type your password: ')
    for char in special_character:
        if char in password:
            print('Password Created!!')
            created = True
            break
    
    else:
        print('Sorry, try again!')