-2

How can I regroup all the symbols like "!@#$%^&*()_+[]{}'\"|./?><" and use them, if the variable contains the symbols it will return False?

I'm trying to create a code for the password, and if the password contains only symbols like "!@#$%^&*()_+[]{}'\"|./?><", return False.

medium-dimensional
  • 1,974
  • 10
  • 19
  • Does this answer your question? [How to check a string for specific characters?](https://stackoverflow.com/questions/5188792/how-to-check-a-string-for-specific-characters) – Javad Nov 13 '22 at 11:19

2 Answers2

1

If you're interested in checking that a string s consists only of symbols from t = "!@#$%^&*()_+[]{}'\"|./?><", then you can do something like:

t = set(t)

all(c in t for c in s)  # This will be True if s consists only of symbols from t

EDIT: Improved the code according to @rioV8 's comment

abel1502
  • 955
  • 4
  • 14
  • Why do you need to convert it into a set? `in` works for strings as well. – The Myth Nov 12 '22 at 21:31
  • 1
    @the-myth , true, but it's more efficient for sets: O(1) as opposed to O(n) (since python's set is a hashset). It probably won't make that much of a difference with such small strings, but there's certainly no harm in it – abel1502 Nov 12 '22 at 21:35
  • 1
    why convert to a list first before iteration, why not use a generator expression, `all` will terminate faster – rioV8 Nov 12 '22 at 21:58
  • @rioV8 that's a good point, actually – abel1502 Nov 12 '22 at 22:01
1

Here's my code:

def check_pwd(pwd):
    symbols = "!@#$%^&*()_+[]{}'\"|./?><" # \" instead of "
    if all(char in symbols for char in pwd): # checks if all characters of pwd in symbols
        return False
    return True

print(check_pwd("##"))

You could also shorten your code into:

symbols = set("!@#$%^&*()_+[]{}'\"|./?><")

def check_pwd(pwd):
    return not all(char in symbols for char in pwd)

See the documentation for all().

ddejohn
  • 8,775
  • 3
  • 17
  • 30
The Myth
  • 1,090
  • 1
  • 4
  • 16