首页 > 解决方案 > 如何检查python中的字符串是否包含来自另一个字符串的随机字符集

问题描述

我有一个源词作为字符串,我有一个字符串,人们在其中输入一个单词列表,但是我如何检查输入的字符串是否只包含来自源词的字符,但顺序不限

def check(input_string):
    import re
    #http://docs.python.org/library/re.html
    #re.search returns None if no position in the string matches the pattern
    #pattern to search for any character other then . a-z 0-9
    pattern =word
    if re.search(pattern, test_str):
        #Character other then . a-z 0-9 was found
        print('Invalid : %r' % (input_string,))
    else:
        #No character other then . a-z 0-9 was found
        print('Valid   : %r' % (input_string,))```

标签: pythonwindows

解决方案


使用set,它支持检查子集。

template = set(word)
if set(input_string) < template:
    print("OK")

如果您坚持使用正则表达式,请将模板转换为字符类:

template = re.compile(f'[{word}]+')
if template.fullmatch(input_string):
    print("OK")

推荐阅读