Subeen Regmi
Subeen Regmi

Reputation: 46

Check if string only contains characters from list of characters/symbols?

How can I check in Python 3 that a string contains only characters/symbols from a given list?

Given:

How do I check if enteredpass only contains characters from the list allowedSymbols?

Upvotes: 2

Views: 7989

Answers (4)

smci
smci

Reputation: 33970

The more Pythonic way is to use all(), it's faster, shorter, clearer and you don't need a loop:

allowedSymbols = ['b', 'c', 'z', ':']

enteredpass1 = 'b:c::z:bc:'
enteredpass2 = 'bc:y:z'

# We can use a list-comprehension... then apply all() to it...
>>> [c in allowedSymbols for c in enteredpass1]
[True, True, True, True, True, True, True, True, True, True]

>>> all(c in allowedSymbols for c in enteredpass1)
True
>>> all(c in allowedSymbols for c in enteredpass2)
False

Also note there's no gain in allowedSymbols being a list of chars instead of a simple string: allowedSymbols = 'bcz:' (The latter is more compact in memory and probably tests faster too)

But you can easily convert the list to a string with ''.join(allowedSymbols)

>>> allowedSymbols_string = 'bcz:'

>>> all(c in allowedSymbols_string for c in enteredpass1)
True
>>> all(c in allowedSymbols_string for c in enteredpass2)
False

Please see the doc for the helpful builtins any() and all(), together with list comprehensions or generator expressions they are very powerful.

Upvotes: 5

wwii
wwii

Reputation: 23783

Use sets for membership testing: keep the symbols in a set then check if it is a superset of the string.

>>> allowed = {'b', 'c', 'z', ':'}
>>> pass1 = 'b:c::z:bc:'
>>> allowed.issuperset(pass1)
True
>>> pass2 = 'f:c::z:bc:'
>>> allowed.issuperset(pass2)
False
>>> allowed.issuperset('bcz:')
True

Upvotes: 3

Michael
Michael

Reputation: 869

This should do it.

for i in enteredpass:
    if i not in allowedSymbols:
         print("{} character is not allowed".format(i))
         break

Not sure what you're looking for with the Score = score -5. If you want to decrease score by 5 if all entered characters are in the allowedSymbols list just put score = score - 5 on the same indentation level as the for loop, but at the end of the code after the if block.

Upvotes: 0

user2644503
user2644503

Reputation: 1573

I am not a python expert, but something below will work

 for c in enteredpass:
   if c not in allowedSymbols: 
      return 0

Upvotes: 0

Related Questions