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

前端 未结 4 1732
野的像风
野的像风 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: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.

提交回复
热议问题