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

前端 未结 4 1726
野的像风
野的像风 2021-01-28 03:44

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\', \'
相关标签:
4条回答
  • 2021-01-28 04:08

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

     for c in enteredpass:
       if c not in allowedSymbols: 
          return 0
    
    0 讨论(0)
  • 2021-01-28 04:13

    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.

    0 讨论(0)
  • 2021-01-28 04:15

    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
    
    0 讨论(0)
  • 2021-01-28 04:30

    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.

    0 讨论(0)
提交回复
热议问题