如何在 Python 3 中检查字符串是否仅包含给定列表中的字符/符号?
鉴于:
allowedSymbols = ['b', 'c', 'z', ':']enteredpass = str(input("Enter"))如何检查是否enteredpass仅包含列表中的字符allowedSymbols?
更 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(),与列表推导式或生成器表达式一起使用,它们非常强大。
| 归档时间: |
|
| 查看次数: |
7438 次 |
| 最近记录: |