如何在Python中扫描字符串中的特定字符?
如果要检查字符串中是否存在给定字符,则可以使用in。例如,
>>> s = "Hello world" >>> 'e' in s True
如果您有要搜索的字符列表,则可以使用集合。将这些字符添加到集合中,然后使用any函数检查字符串中是否存在这些字符。例如,
from sets import Set
chars = Set('0123456789$,')
s = "I have 9 cats"
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')这将给出输出:
Found
如果要检查字符串中是否所有这些字符,只需将它们全部替换。例如,
from sets import Set
chars = Set('0123456789$,')
s = "I have 9 cats"
if all((c in chars) for c in s):
print('Found')
else:
print('Not Found')这将给出输出:
Not Found
热门推荐
10 酒店中秋送祝福语简短
11 关于决赛的祝福语简短
12 满月祝福语长辈妈妈简短
13 毕业祝福语惊艳句子简短
14 酒店送水果祝福语简短
15 工作轮岗祝福语大全简短
16 明天考试祝福语长辈简短
17 儿子榴莲蛋糕祝福语简短
18 看孕妈祝福语简短