首页 > 解决方案 > 如何检查某些特定字符不在字符串中

问题描述

我正在尝试检查一个符号(例如(ab))是否不在字符串中。我写了下面的代码,但它不能正常工作。

name = input("please enter name ")

while ("a" or "b" or "c" or "d") in name:
    name = input("please retry")

标签: python

解决方案


一种可能的变体是使用集合:

while {'a', 'b', 'c', 'd'}.intersection(name):

您可以将此集合存储到某个变量:

bad_characters = {'a', 'b', 'c', 'd'}

name = input('name:')
while bad_characters.intersection(name):
    name = input('name:')

推荐阅读