检查另一个字符串中是否存在多个字符串

问题描述 投票:296回答:13

如何检查数组中的任何字符串是否存在于另一个字符串中?

喜欢:

a = ['a', 'b', 'c']
str = "a123"
if a in str:
  print "some of the strings found in str"
else:
  print "no strings found in str"

该代码不起作用,只是为了展示我想要实现的目标。

python arrays string exists
13个回答
594
投票

你可以使用any

if any(x in str for x in a):

类似于检查是否找到列表中的所有字符串,使用all而不是any


0
投票

我会使用这种功能来提高速度:

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False

0
投票
data = "firstName and favoriteFood"
mandatory_fields = ['firstName', 'lastName', 'age']


# for each
for field in mandatory_fields:
    if field not in data:
        print("Error, missing req field {0}".format(field));

# still fine, multiple if statements
if ('firstName' not in data or 
    'lastName' not in data or
    'age' not in data):
    print("Error, missing a req field");

# not very readable, list comprehension
missing_fields = [x for x in mandatory_fields if x not in data]
if (len(missing_fields)>0):
    print("Error, missing fields {0}".format(", ".join(missing_fields)));

0
投票

关于如何在String中获取所有列表元素的更多信息

a = ['a', 'b', 'c']
str = "a123" 
list(filter(lambda x:  x in str, a))

0
投票

一个令人惊讶的快速方法是使用set

a = ['a', 'b', 'c']
str = "a123"
if set(a) & set(str):
    print("some of the strings found in str")
else:
    print("no strings found in str")

如果a不包含任何多字符值(在这种情况下使用any列为above),则此方法有效。如果是这样,将a指定为字符串更简单:a = 'abc'


54
投票

any()是迄今为止最好的方法,如果你想要的只是TrueFalse,但如果你想知道哪些字符串/字符串匹配,你可以使用几个东西。

如果你想要第一场比赛(默认使用False):

match = next((x for x in a if x in str), False)

如果你想得到所有的比赛(包括重复):

matches = [x for x in a if x in str]

如果您想获得所有非重复匹配(忽略订单):

matches = {x for x in a if x in str}

如果您想以正确的顺序获得所有非重复匹配:

matches = []
for x in a:
    if x in str and x not in matches:
        matches.append(x)

40
投票

如果astr中的字符串变长,你应该小心。直接的解决方案采用O(S *(A ^ 2)),其中Sstr的长度,A是a中所有字符串长度的总和。要获得更快的解决方案,请查看用于字符串匹配的Aho-Corasick算法,该算法以线性时间O(S + A)运行。


16
投票

只是为了增加regex的多样性:

import re

if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
    print 'possible matches thanks to regex'
else:
    print 'no matches'

或者如果你的名单太长 - any(re.findall(r'|'.join(a), str, re.IGNORECASE))


8
投票

你需要迭代a的元素。

a = ['a', 'b', 'c']
str = "a123"
found_a_string = False
for item in a:    
    if item in str:
        found_a_string = True

if found_a_string:
    print "found a match"
else:
    print "no match found"

3
投票
a = ['a', 'b', 'c']
str =  "a123"

a_match = [True for match in a if match in str]

if True in a_match:
  print "some of the strings found in str"
else:
  print "no strings found in str"

2
投票

jbernadas已经提到了Aho-Corasick-Algorithm以降低复杂性。

以下是在Python中使用它的一种方法:

  1. here下载aho_corasick.py
  2. 将它放在与主Python文件相同的目录中,并将其命名为aho_corasick.py
  3. 使用以下代码尝试alrorithm: from aho_corasick import aho_corasick #(string, keywords) print(aho_corasick(string, ["keyword1", "keyword2"]))

请注意,搜索区分大小写


1
投票

这取决于上下文假设你想要检查单个文字(任何一个单词a,e,w,..等)就足够了

original_word ="hackerearcth"
for 'h' in original_word:
      print("YES")

如果你想检查original_word中的任何一个字符:make use

if any(your_required in yourinput for your_required in original_word ):

如果你想在原始文字中输入你想要的所有内容,请使用所有简单的内容

original_word = ['h', 'a', 'c', 'k', 'e', 'r', 'e', 'a', 'r', 't', 'h']
yourinput = str(input()).lower()
if all(requested_word in yourinput for requested_word in original_word):
    print("yes")

0
投票
flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
     for fstr in strlist:
         if line.find(fstr) != -1:
            print('found') 
            res = True


if res:
    print('res true')
else: 
    print('res false')

output example image

© www.soinside.com 2019 - 2024. All rights reserved.