there are two strings:
str1 = "black_red_yellow"
str2 = "blue_red_green"
which python library can I use to check these two strings have a substring"_red_"
in common? thank you in advance.
there are two strings:
str1 = "black_red_yellow"
str2 = "blue_red_green"
which python library can I use to check these two strings have a substring"_red_"
in common? thank you in advance.
Something like this should work if you don't know the actual string you're searching for
import difflib
str1 = "black_red_yellow"
str2 = "blue_red_green"
difference = difflib.SequenceMatcher()
difference.set_seqs(str1, str2)
for match in difference.get_matching_blocks():
print str1[match[0]:match[0] + match[2]]
if set(str1).intersection(set(str2)): print "yes we can!"
You can use difflib to compare strings in that way. However, if you know the string you're looking for you could just do '_red_' in str1 and '_red_' in str2
. If you don't know the string, then do you look for a specific length of match? E.g. would 'red'
match 'blue'
because they both contain 'e'
? The shortest, simplest way of checking for any match at all would be
bool([a for a in str1 if a in str2])
Edit: Or, more efficiently,
any(a for a in str1 if a in str2)
if you can't find anything else, then there's at least this naive implementation:
str1 = "black_red_yellow"
str2 = "blue_red_green"
if len(str1) < len(str2):
min_str = str1
max_str = str2
else:
min_str = str2
max_str = str1
matches = []
min_len = len(min_str)
for b in xrange(min_len):
for e in xrange(min_len, b, -1):
chunk = min_str[b:e]
if chunk in max_str:
matches.append(chunk)
print max(matches, key=len)
prints _red_