Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare an input to strings in a list in Python? [duplicate]

I want to create a password program that checks to see if a special character is inside an input.

So I created a list with some special characters so that if just one or multiple symbols are detected in the input, then it should do something:

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

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

I think I need to use a for loop as well in which case it prints all items. Or I may need to check just specific characters and not the entire input, how do I do this?

like image 998
Altaic Avatar asked Oct 22 '25 23:10

Altaic


2 Answers

You can use any (if there should be at least one special char from the list) or all if there must be all special chars from the list in the input string.

if any(x in SpecialSymbols for x in Password):
if all(x in SpecialSymbols for x in Password):

See a Python demo:

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")

Output for this snippet:

strong password
strong password
no special character detected
like image 88
Wiktor Stribiżew Avatar answered Oct 24 '25 14:10

Wiktor Stribiżew


Loop through the string

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')
like image 28
Sid Avatar answered Oct 24 '25 13:10

Sid