python - 如何检查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,))```
解决方案
使用set
,它支持检查子集。
template = set(word)
if set(input_string) < template:
print("OK")
如果您坚持使用正则表达式,请将模板转换为字符类:
template = re.compile(f'[{word}]+')
if template.fullmatch(input_string):
print("OK")
推荐阅读
- html - Electron 不加载 html body 但加载 head
- javascript - 在 R Shiny 的 Rhandsontable 中使用 manualMove 后获取 afterRowMove 回调
- facebook - 获取“页面公共内容访问需要应用程序秘密证明或应用程序令牌”
- html - 如何让 VSCode 读取我的导航代码?
- reactjs - 在 react typescript 组件上实现 RouteComponentProps 时使用什么类型
- javascript - 在从客户端 Jquery Laravel 上传之前预先调整多个图像的大小
- kotlin - 动态更新 tornadofx 中的折线点
- r - 一次构建(或删除)ggplot facet 的面板
- julia - 如何按索引元素的 N 数组访问多维数组?
- node.js - NodeJs 和 Jest:模拟 Mongoose 多次调用 find().sort().limit()