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

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

提交回复
热议问题