Skip to content Skip to sidebar Skip to footer

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: a list allowedSymbols = ['b', 'c', 'z', ':'] an input string enteredpass = str

Solution 1:

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.


Solution 2:

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

Solution 3:

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

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

Solution 4:

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.


Post a Comment for "Check If String Only Contains Characters From List Of Characters/symbols?"