【问题标题】:How to check if a certain part of a string is in a set of strings in Python?如何检查字符串的某个部分是否在 Python 中的一组字符串中?
【发布时间】:2020-03-07 17:41:30
【问题描述】:

如果我有一个字符串列表

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

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

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

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

【问题讨论】:

  • 你试过什么?从技术上讲,set1list,而不是 set。并且\land 不在set1 中,除非您寻找一些部分/模糊匹配。列表元素也不在\land 字符串中。在这种情况下,您需要澄清您的问题/提供更多信息。
  • 我很困惑...(\lor 不在set1 中,但set1 中的一项在(\lor 中。你是这个意思吗?然后any(s in "(\\lor" for s in set1) 就可以了。
  • 是的,你是对的,它是一个列表。但是 '\land' 在 set1 中,因为 '\\land' 是 Python 存储 '\land' 的方式。
  • @tdelaney ,基本上我希望像 '(\lor'、'xyz\lor' 和 '))\lor' 这样的字符串在 set1 中返回 true,因为这些字符串包含 '/lor',这是 set1 的一个元素。
  • 是的,我的错,我忽略了转义序列

标签: python arrays string list


【解决方案1】:

看看这是否适合你:

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'

【讨论】:

  • 谢谢,如果我只检查一个字符串而不是字符串列表,我该如何更改?
  • 你知道我怎么能把字符串分成两部分吗?如果我有 '(\lor' 我怎么能得到 '(' 和 '\\lor'
  • @Biggeez,我已经更新了答案,看看这是不是你需要的
  • 更具体地说,如果我有'Predicate(big,small)' 字符串,我怎么能把它分成一个大小为六的列表? ['Predicate','(','big','small',')']
猜你喜欢
  • 2019-07-19
  • 2019-08-05
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
相关资源
最近更新 更多