如何在Python中将输入与列表中的字符串进行比较?

3

我希望创建一个密码程序,能够检查输入中是否有特定的字符。

因此,我创建了一个包含一些特殊字符的列表,以便在输入中检测到一个或多个符号时,应该执行某些操作:

SpecialSymbols =['$', '@', '#', '%']
Password = input("type password")

if Password in SpecialSymbols:
    print("strong password")
else:
    print("no special character detected")

我认为我需要使用一个for循环,这样它就可以打印所有的项目。或者我只需要检查特定的字符而不是整个输入,我该怎么做?

1
如果 Password 中的所有字符都在 SpecialSymbols 中,则输出 "strong password",可以使用第一个 if 语句;如果 Password 中有任何一个字符在 SpecialSymbols 中出现,则输出 "strong password",可以使用第二个 if 语句。 - Wiktor Stribiżew
1
你是想说 if SpecialSymbols in Password: 吗? - D_00
1
strong = False for symbol in SpecialSymbols:if symbol in Password:strong=True if strong:print(strong password) - 如果一行打印多行不清晰,请告诉我。 - D_00
4个回答

3
您可以使用any(如果输入字符串中应至少有列表中的一个特殊字符)或all(如果输入字符串中必须有列表中的所有特殊字符)来实现。
if any(x in SpecialSymbols for x in Password):
if all(x in SpecialSymbols for x in Password):

请参见Python演示

SpecialSymbols =['$', '@', '#', '%']
Passwords = ["String #$%@", "String #1", "String"]
for Password in Passwords:
    if any(x in SpecialSymbols for x in Password):
        print("strong password")
    else:
        print("no special character detected")

这段代码的输出结果是:
strong password
strong password
no special character detected

3

遍历字符串

SpecialSymbols =['$', '@', '#', '%']
Password = input("type password")
strong = False
for c in Password:
    if c in SpecialSymbols:
        strong = True
        break
if strong:
    print("Password is strong")
else:
    print('password is weak')

2

这段代码检测密码中有多少个特殊字符。

SpecialSymbols =['$', '@', '#', '%']
Password = input("type password")

number = 0
for symbol in SpecialSymbols: # for each symbol
    if symbol in Password: # check if it is in the password
        number += 1

if number >= 1: # symbol detected in the password
    print("strong password (%d special symbols in)" % number)
else:
    print("no special character detected")

更加简洁:只需检查是否存在任何符号,而不是使用出现次数计数器,而是使用布尔值 strong
strong = False
for symbol in SpecialSymbols:
    if symbol in Password:
        strong = True
        break

if strong:
    print("strong password")
else:
    print("no special character detected")

2
为了解决您的问题,我创建了一个函数,将检查单词中的每个字母是否为特殊字符。如果是,则会增加“分数”并返回true。然后您可以将此函数用于输入密码。
以下是代码:
SpecialSymbols =['$', '@', '#', '%']
Password = input("type password")

def strongPassword(password):
    score = 0
    for letter in Password:
        for spec in SpecialSymbols:
            if letter == spec :
                score = score + 1
    print(score)
    if score : 
        return True

strongPassword(Password)

if strongPassword(Password):
    print("strong password")
else:
    print("no special character detected")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接