繁体   English   中英

如何检查字符串的某个部分是否在 Python 中的一组字符串中?

[英]How to check if a certain part of a string is in a set of strings in Python?

如果我有一个字符串列表

set1 = ['\\land','\\lor','\\implies']

我想扫描一个字符串列表并检查是否有任何字符串包含其中的 set 元素。

字符串'\\land'将在 set1 中返回 true

但是,我将如何检查'(\\lor'是否在 set1 中?

看看这是否适合你:

import re

set1 = ['\\land','\\lor','\\implies']
strings = ['\land', '(\lor']

r = re.compile('|'.join([re.escape(w) for w in set1]), flags=re.I)

for i in strings:
    print(r.findall(i))

这个的输出是

['\\land']
['\\lor']

**** 修改 - 如果有一个字符串**

import re

set1 = ['\\land','\\lor','\\implies']
strings = '(\lor'

r = re.compile('|'.join([re.escape(w) for w in set1]), flags=re.I)

print(r.findall(strings))

** 如果您只想将特殊字符 "(" 从 "(\\lor" 中删除,我们可以这样做:

>>> a = '(\lor'
>>> a.split('(')[1]
'\\lor'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM