检查字符串是否仅包含字符/符号列表中的字符?

Sub*_*gmi 2 python python-3.x

如何在 Python 3 中检查字符串是否仅包含给定列表中的字符/符号?

鉴于:

  • 一个列表allowedSymbols = ['b', 'c', 'z', ':']
  • 输入字符串enteredpass = str(input("Enter"))

如何检查是否enteredpass仅包含列表中的字符allowedSymbols?

smc*_*mci 5

更 Pythonic 的方法是使用all(),它更快、更短、更清晰,而且不需要循环:

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
Run Code Online (Sandbox Code Playgroud)

另请注意,作为字符列表而不是简单的字符串没有任何好处allowedSymbolsallowedSymbols = 'bcz:':(后者在内存中更紧凑,并且可能测试速度也更快)

但是您可以轻松地将列表转换为字符串''.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
Run Code Online (Sandbox Code Playgroud)

请参阅文档以获取有用的内置函数any()和all(),与列表推导式或生成器表达式一起使用,它们非常强大。