intersection of 2 strings

Jørgen Cederberg jorgencederberg at hotmail.com
Tue Aug 3 16:05:16 CEST 2004


Antoine Logean wrote:
> Hi,
> 
> What is the easiest way to get the intersection of two strings in
> python (a kind a "and" operator) ?
> ex:
> 
> string_1 = "the_car_of_my_fried_is_bigger_as_mine_but_my_girlfriend_is_more_beautifull"
> 
> string_2 =
> "my_girlfriend_is_more_beautifull_and_has_blue_eyes"
> 
> and the intersection :
> string_1 "and" string_2 = "my_girlfriend_is_more_beautifull"
> 
> thanks for your help
> 
> Antoine

Hi

difflib seems to appropiate, http://docs.python.org/lib/module-difflib.html
and especially
http://docs.python.org/lib/sequence-matcher.html

Here is some code that works

from difflib import SequenceMatcher
s1 = "my_girlfriend_is_a_python"
s2 = "my_girlfriend_is_more_beautifull"
m = SequenceMatcher(None, s1, s2)
print "Matches between: %s and %s" %(s1,s2)
for match in m.get_matching_blocks():
     i,j,n = match
     if n>1:               # We don't want to match single chars.
         print s1[i:i+n]

HTH
Jorgen Cederberg



More information about the Python-list mailing list