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

时间:2019-07-09 23:30:28

标签: python python-3.x

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

给出:

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

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

4 个答案:

答案 0 :(得分:1)

更Python化的方式是使用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

还请注意,allowedSymbols作为一个字符列表而不是简单的字符串是没有好处的:allowedSymbols = '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

see the doc for the helpful builtins any() and all()以及列表推导或生成器表达式非常强大。

答案 1 :(得分:1)

使用集合进行成员资格测试:将符号保留在集合中,然后检查它是否为字符串的超集。

>>> 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

答案 2 :(得分:0)

这应该做到。

for i in enteredpass:
    if i not in allowedSymbols:
         print("{} character is not allowed".format(i))
         break

不确定得分=得分-5是什么。 如果要在所有输入的字符都在allowedSymbols列表中的情况下将分数降低5,则只需将score = score-5与for循环的缩进级别相同,但要在代码末尾的if块之后。

答案 3 :(得分:0)

我不是python专家,但是下面的方法会起作用

=[docNum]